home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Offline Browsing / HTTrack.exe / data1.cab / Sources / src / htslib.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-04-28  |  82.5 KB  |  3,086 lines

  1. /* ------------------------------------------------------------ */
  2. /*
  3. HTTrack Website Copier, Offline Browser for Windows and Unix
  4. Copyright (C) Xavier Roche and other contributors
  5.  
  6. This program is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU General Public License
  8. as published by the Free Software Foundation; either version 2
  9. of the License, or any later version.
  10.  
  11. This program is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with this program; if not, write to the Free Software
  18. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  19.  
  20.  
  21. Important notes:
  22.  
  23. - We hereby ask people using this source NOT to use it in purpose of grabbing
  24. emails addresses, or collecting any other private information on persons.
  25. This would disgrace our work, and spoil the many hours we spent on it.
  26.  
  27.  
  28. Please visit our Website: http://www.httrack.com
  29. */
  30.  
  31.  
  32. /* ------------------------------------------------------------ */
  33. /* File: Subroutines                                            */
  34. /* Author: Xavier Roche                                         */
  35. /* ------------------------------------------------------------ */
  36.  
  37. // Fichier librairie .c
  38.  
  39. #include "htslib.h"
  40. #include "htsbauth.h"
  41.  
  42. /* specific definitions */
  43. #include "htsbase.h"
  44. #include "htsnet.h"
  45. #include "htsbauth.h"
  46. #include "htsthread.h"
  47. #include <stdio.h>
  48. #include <stdlib.h>
  49. #include <string.h>
  50. #include <time.h>
  51. #include <sys/timeb.h>
  52. #include <fcntl.h>
  53. // pour utimbuf
  54. #if HTS_WIN
  55. #include <sys/utime.h>
  56. #else
  57. #if HTS_PLATFORM!=3
  58. #include <utime.h>
  59. #else
  60. #include <utime.h>
  61. #endif
  62. #endif
  63. /* END specific definitions */
  64.  
  65.  
  66.  
  67. // DΘbuggage de contr⌠le
  68. #if HTS_DEBUG_CLOSESOCK
  69. #define _HTS_WIDE 1
  70. #endif
  71. #if HTS_WIDE_DEBUG
  72. #define _HTS_WIDE 1
  73. #endif
  74. #if _HTS_WIDE
  75. FILE* DEBUG_fp=NULL;
  76. #define DEBUG_W(A)  { if (DEBUG_fp==NULL) DEBUG_fp=fopen("bug.out","wb"); fprintf(DEBUG_fp,":>"A); fflush(DEBUG_fp); }
  77. #define DEBUG_W2(A) { if (DEBUG_fp==NULL) DEBUG_fp=fopen("bug.out","wb"); fprintf(DEBUG_fp,A); fflush(DEBUG_fp); }
  78. #endif
  79.  
  80. /* variables globales */
  81. int _DEBUG_HEAD;
  82. FILE* ioinfo;
  83.  
  84. /* dΘtection complΘmentaire */
  85. const char hts_detect[][32] = {
  86.   "archive",
  87.   "background",
  88.   "dynsrc",
  89.   "lowsrc",
  90.   "src",
  91.   "url",
  92.   ""
  93. };
  94.  
  95. /* dΘtection de mini-code javascript */
  96. /* ALSO USED: detection based on the name: onXXX="<tag>" where XXX starts with upper case letter */
  97. const char hts_detect_js[][32] = {
  98.   "onAbort",
  99.   "onBlur",
  100.   "onChange",
  101.   "onClick",
  102.   "onDblClick",
  103.   "onDragDrop",
  104.   "onError",
  105.   "onFocus",
  106.   "onKeyDown",
  107.   "onKeyPress",
  108.   "onKeyUp",
  109.   "onLoad",
  110.   "onMouseDown",
  111.   "onMouseMove",
  112.   "onMouseOut",
  113.   "onMouseOver",
  114.   "onMouseUp",
  115.   "onMove",
  116.   "onReset",
  117.   "onResize",
  118.   "onSelect",
  119.   "onSubmit",
  120.   "onUnload",
  121.   ""
  122. };
  123.  
  124. /* dΘtection "...URL=<url>" */
  125. const char hts_detectURL[][32] = {
  126.   "content",
  127.   ""
  128. };
  129.  
  130. /* tags o∙ l'URL doit Ωtre rΘΘcrite mais non capturΘe */
  131. const char hts_detectandleave[][32] = {
  132.   "action",
  133.   ""
  134. };
  135.  
  136. /* ne pas renommer les types renvoyΘs (couvent types inconnus) */
  137. const char hts_mime_keep[][32] = {
  138.   "application/octet-stream",
  139.   "text/plain",
  140.   ""
  141. };
  142.  
  143. /* types MIME */
  144. const char hts_mime[][2][32] = {
  145.   {"application/acad","dwg"},
  146.   {"application/arj","arj"},
  147.   {"application/clariscad","ccad"},
  148.   {"application/drafting","drw"},
  149.   {"application/dxf","dxf"},
  150.   {"application/excel","xl"},
  151.   {"application/i-deas","unv"},
  152.   {"application/iges","isg"},
  153.   {"application/iges","iges"},
  154.   {"application/mac-binhex40","hqx"},
  155.   {"application/mac-compactpro","cpt"},
  156.   {"application/msword","word"},
  157.   {"application/msword","w6w"},
  158.   {"application/msword","doc"},
  159.   {"application/mswrite","wri"},
  160.   /*{"application/octet-stream","dms"},*/
  161.   /*{"application/octet-stream","lzh"},*/
  162.   /*{"application/octet-stream","lha"},*/
  163.   /*{"application/octet-stream","bin"},*/
  164.   {"application/oda","oda"},
  165.   {"application/pdf","pdf"},
  166.   {"application/postscript","ai"},
  167.   {"application/postscript","ps"},
  168.   {"application/postscript","eps"},
  169.   {"application/powerpoint","ppt"},
  170.   {"application/pro_eng","prt"},
  171.   {"application/pro_eng","part"},
  172.   {"application/rtf","rtf"},
  173.   {"application/set","set"},
  174.   {"application/sla","stl"},
  175.   {"application/smil","smi"},
  176.   {"application/smil","smil"},
  177.   {"application/smil","sml"},
  178.   {"application/solids","sol"},
  179.   {"application/STEP","stp"},
  180.   {"application/STEP","step"},
  181.   {"application/vda","vda"},
  182.   {"application/x-authorware-map","aam"},     
  183.   {"application/x-authorware-seg","aas"},
  184.   {"application/x-authorware-bin","aab"},
  185.   {"application/x-cocoa","cco"},
  186.   {"application/x-csh","csh"},
  187.   {"application/x-director","dir"},
  188.   {"application/x-director","dcr"},
  189.   {"application/x-director","dxr"},
  190.   {"application/x-mif","mif"},
  191.   {"application/x-dvi","dvi"},
  192.   {"application/x-gzip","gz"},
  193.   {"application/x-gzip","gzip"},
  194.   {"application/x-hdf","hdf"},
  195.   {"application/x-javascript","js"},
  196.   {"application/x-koan","skp"},
  197.   {"application/x-koan","skd"},
  198.   {"application/x-koan","skt"},
  199.   {"application/x-koan","skm"},
  200.   {"application/x-latex","latex"},
  201.   {"application/x-netcdf","nc"},
  202.   {"application/x-netcdf","cdf"},
  203.   /* {"application/x-sh","sh"}, */
  204.   /* {"application/x-csh","csh"}, */
  205.   /* {"application/x-ksh","ksh"}, */
  206.   {"application/x-shar","shar"},
  207.   {"application/x-stuffit","sit"},
  208.   {"application/x-tcl","tcl"},
  209.   {"application/x-tex","tex"},
  210.   {"application/x-texinfo","texinfo"},
  211.   {"application/x-texinfo","texi"},
  212.   {"application/x-troff","t"},
  213.   {"application/x-troff","tr"},
  214.   {"application/x-troff","roff"},
  215.   {"application/x-troff-man","man"},
  216.   {"application/x-troff-me","ms"},
  217.   {"application/x-wais-source","src"},
  218.   {"application/zip","zip"},
  219.   {"application/x-bcpio","bcpio"},
  220.   {"application/x-cdlink","vcd"},
  221.   {"application/x-cpio","cpio"},
  222.   {"application/x-gtar","tgz"},
  223.   {"application/x-gtar","gtar"},
  224.   {"application/x-shar","shar"},
  225.   {"application/x-shockwave-flash","swf"},
  226.   {"application/x-sv4cpio","sv4cpio"},
  227.   {"application/x-sv4crc","sv4crc"},
  228.   {"application/x-tar","tar"},
  229.   {"application/x-ustar","ustar"},
  230.   {"application/x-winhelp","hlp"},
  231.   {"audio/midi","mid"},
  232.   {"audio/midi","midi"},
  233.   {"audio/midi","kar"},
  234.   {"audio/mpeg","mp3"},
  235.   {"audio/mpeg","mpga"},
  236.   {"audio/mpeg","mp2"},
  237.   {"audio/basic","au"},
  238.   {"audio/basic","snd"},
  239.   {"audio/x-aiff","aif"},
  240.   {"audio/x-aiff","aiff"},
  241.   {"audio/x-aiff","aifc"},
  242.   {"audio/x-pn-realaudio","ra"},
  243.   {"audio/x-pn-realaudio","ram"},
  244.   {"audio/x-pn-realaudio","rm"},
  245.   {"audio/x-pn-realaudio-plugin","rpm"},
  246.   {"audio/x-wav","wav"},
  247.   {"chemical/x-pdb","pdb"},
  248.   {"chemical/x-pdb","xyz"},
  249.   {"drawing/x-dwf","dwf"},
  250.   {"image/gif","gif"},
  251.   {"image/ief","ief"},
  252.   {"image/jpeg","jpg"},
  253.   {"image/jpeg","jpe"},
  254.   {"image/jpeg","jpeg"},
  255.   {"image/pict","pict"},
  256.   {"image/png","png"},
  257.   {"image/tiff","tiff"},
  258.   {"image/tiff","tif"},
  259.   {"image/x-cmu-raster","ras"},
  260.   {"image/x-freehand","fh4"},
  261.   {"image/x-freehand","fh7"},
  262.   {"image/x-freehand","fh5"},  
  263.   {"image/x-freehand","fhc"},
  264.   {"image/x-freehand","fh"},   
  265.   {"image/x-portable-anymap","pnm"},
  266.   {"image/x-portable-bitmap","pgm"},
  267.   {"image/x-portable-pixmap","ppm"},
  268.   {"image/x-rgb","rgb"},
  269.   {"image/x-xbitmap","xbm"},
  270.   {"image/x-xpixmap","xpm"},
  271.   {"image/x-xwindowdump","xwd"},
  272.   {"model/mesh","msh"},  
  273.   {"model/mesh","mesh"},  
  274.   {"model/mesh","silo"},  
  275.   {"multipart/x-zip","zip"},
  276.   {"multipart/x-gzip","gzip"},
  277.   {"text/css","css"},
  278.   {"text/html","html"},
  279.   {"text/html","htm"},
  280.   {"text/plain","txt"},
  281.   {"text/plain","g"},
  282.   {"text/plain","h"},
  283.   {"text/plain","c"},
  284.   {"text/plain","cc"},
  285.   {"text/plain","hh"},
  286.   {"text/plain","m"},
  287.   {"text/plain","f90"},
  288.   {"text/richtext","rtx"},
  289.   {"text/tab-separated-values","tsv"},
  290.   {"text/x-setext","etx"},
  291.   {"text/x-sgml","sgml"},
  292.   {"text/x-sgml","sgm"},
  293.   {"text/xml","xml"},  
  294.   {"text/xml","dtd"},  
  295.   {"video/mpeg","mpeg"},
  296.   {"video/mpeg","mpg"},
  297.   {"video/mpeg","mpe"},
  298.   {"video/quicktime","qt"},
  299.   {"video/quicktime","mov"},
  300.   {"video/x-msvideo","avi"},
  301.   {"video/x-sgi-movie","movie"},
  302.   {"x-conference/x-cooltalk","ice"},
  303.   /*{"application/x-httpd-cgi","cgi"},*/
  304.   {"x-world/x-vrml","wrl"},
  305.   
  306.   {"*","class"},
  307.   
  308.   {"",""}};
  309.  
  310.  
  311.   
  312. // conversion Θventuelle / vers antislash
  313. #if HTS_WIN
  314. char* antislash(char* s) {
  315.   static char buff[HTS_URLMAXSIZE*2];
  316.   static char* a;
  317.   strcpy(buff,s);
  318.   while(a=strchr(buff,'/')) *a='\\';
  319.   return buff;
  320. }
  321. #endif
  322.  
  323.  
  324.  
  325. // RΘcupΘration d'un fichier http sur le net.
  326. // Renvoie une adresse sur le bloc de mΘmoire, ou bien
  327. // NULL si un retour.msgeur (buffer retour.msg) est survenue. 
  328. //
  329. // Une adresse de structure htsmsg peut Ωtre transmise pour
  330. // suivre l'Θvolution du chargement si le process a ΘtΘ lancΘ 
  331. // en background
  332.  
  333. htsblk httpget(char* url) {
  334.   char adr[HTS_URLMAXSIZE*2];   // adresse
  335.   char fil[HTS_URLMAXSIZE*2];   // chemin
  336.   
  337.   // sΘparer URL en adresse+chemin
  338.   if (ident_url(url,adr,fil)==-1) {
  339.     htsblk retour;
  340.     bzero((char *)&retour, sizeof(htsblk));    // effacer
  341.     // retour prΘdΘfini: erreur
  342.     retour.adr=NULL;
  343.     retour.size=0;
  344.     retour.msg[0]='\0';
  345.     retour.statuscode=-1;    
  346.     strcpy(retour.msg,"Error invalid URL");
  347.     return retour;
  348.   }
  349.   
  350.   return xhttpget(adr,fil);
  351. }
  352.  
  353. // ouvre une liaison http, envoie une requΦte GET et rΘceptionne le header
  354. // retour: socket
  355. int http_fopen(char* adr,char* fil,htsblk* retour) {
  356.   //                / GET, traiter en-tΩte
  357.   return http_xfopen(0,1,1,NULL,adr,fil,retour);
  358. }
  359.  
  360. // ouverture d'une liaison http, envoi d'une requΦte
  361. // mode: 0 GET  1 HEAD  [2 POST]
  362. // treat: traiter header?
  363. // waitconnect: attendre le connect()
  364. // note: dans retour, on met les params du proxy
  365. int http_xfopen(int mode,int treat,int waitconnect,char* xsend,char* adr,char* fil,htsblk* retour) {
  366.   //htsblk retour;
  367.   //int bufl=TAILLE_BUFFER;    // 8Ko de buffer
  368.   T_SOC soc=INVALID_SOCKET;
  369.   //char *p,*q;
  370.   
  371.   // retour prΘdΘfini: erreur
  372.   if (retour) {
  373.     retour->adr=NULL;
  374.     retour->size=0;
  375.     retour->msg[0]='\0';
  376.     retour->statuscode=-5;          // a priori erreur non fatale
  377.   }
  378.  
  379. #if HDEBUG
  380.   printf("adr=%s\nfichier=%s\n",adr,fil);
  381. #endif
  382.   
  383.   // ouvrir liaison
  384. #if HDEBUG
  385.   printf("CrΘation d'une socket sur %s\n",adr);
  386. #endif
  387.  
  388. #if CNXDEBUG
  389.   printf("..newhttp\n");
  390. #endif
  391.  
  392.   /* connexion */
  393.   if (retour) {
  394.     if ( (!(retour->req.proxy.active)) || (strcmp(adr,"file://")==0) ){    /* pas de proxy, ou non utilisable ici */
  395.       soc=newhttp(adr,retour,-1,waitconnect);
  396.     } else {
  397.       soc=newhttp(retour->req.proxy.name,retour,retour->req.proxy.port,waitconnect);  // ouvrir sur le proxy α la place
  398.     }
  399.   } else {
  400.     soc=newhttp(adr,NULL,-1,waitconnect);    
  401.   }
  402.  
  403.   // copier index socket retour
  404.   if (retour) retour->soc=soc;
  405.  
  406.   // --------------------
  407.   // court-circuit (court circuite aussi le proxy..)
  408.   // LOCAL_SOCKET_ID est une pseudo-socket locale
  409.   if (soc==LOCAL_SOCKET_ID) {
  410.     retour->is_file=1;  // fichier local
  411.     if (mode==0) {    // GET
  412.  
  413.       // Test en cas de file:///C|...
  414.       if (!fexist(fconv(unescape_http(fil))))
  415.         if (fexist(fconv(unescape_http(fil+1)))) {
  416.           char tempo[HTS_URLMAXSIZE*2];
  417.           strcpy(tempo,fil+1);
  418.           strcpy(fil,tempo);
  419.         }
  420.  
  421.       // Ouvrir
  422.       retour->totalsize=fsize(fconv(unescape_http(fil)));  // taille du fichier
  423.       retour->msg[0]='\0';
  424.       soc=INVALID_SOCKET;
  425.       if (retour->totalsize<0)
  426.         strcpy(retour->msg,"Unable to open file");
  427.       else if (retour->totalsize==0)
  428.         strcpy(retour->msg,"File empty");
  429.       else {
  430.         // Note: On passe par un FILE* (plus propre)
  431.         //soc=open(fil,O_RDONLY,0);    // en lecture seule!
  432.         retour->fp=fopen(fconv(unescape_http(fil)),"rb");  // ouvrir
  433.         if (retour->fp==NULL)
  434.           soc=INVALID_SOCKET;
  435.         else
  436.           soc=LOCAL_SOCKET_ID;
  437.       }
  438.       retour->soc=soc;
  439.       if (soc!=INVALID_SOCKET) {
  440.         retour->statuscode=200;   // OK
  441.         strcpy(retour->msg,"OK");
  442.         guess_httptype(retour->contenttype,fil);
  443.       } else if (strnotempty(retour->msg)==0)
  444.           strcpy(retour->msg,"Unable to open file");
  445.       return soc;  // renvoyer
  446.     } else {    // HEAD ou POST : interdit sur un local!!!! (c'est idiot!)
  447.       strcpy(retour->msg,"Unexpected Head/Post local request");
  448.       soc=INVALID_SOCKET;    // erreur
  449.       retour->soc=soc;
  450.       return soc;
  451.     }
  452.   } 
  453.   // --------------------
  454.  
  455.   if (soc!=INVALID_SOCKET) {    
  456.     char rcvd[1100];
  457.     rcvd[0]='\0';
  458. #if HDEBUG
  459.     printf("Ok, connexion rΘussie, id=%d\n",soc);
  460. #endif
  461.     
  462.     // connectΘ?
  463.     if (waitconnect) {
  464.       http_sendhead(NULL,mode,xsend,adr,fil,NULL,NULL,retour);
  465.     } 
  466.     
  467.     if (soc!=INVALID_SOCKET) {
  468.       
  469. #if HDEBUG
  470.       printf("Attente de la rΘponse:\n");
  471. #endif
  472.       
  473.       // si GET (rΘception d'un fichier), rΘceptionner en-tΩte d'abord,
  474.       // et ensuite le corps
  475.       // si POST on ne rΘceptionne rien du tout, c'est aprΦs que l'on fera
  476.       // une rΘception standard pour rΘcupΘrer l'en tΩte
  477.       if ((treat) && (waitconnect)) {  // traiter (attendre!) en-tΩte        
  478.         // RΘception de la status line et de l'en-tΩte (norme RFC1945)
  479.         
  480.         // status-line α rΘcupΘrer
  481.         finput(soc,rcvd,1024);
  482.         if (strnotempty(rcvd)==0)
  483.           finput(soc,rcvd,1024);    // "certains serveurs buggΘs envoient un \n au dΘbut" (RFC)
  484.  
  485.         // traiter status-line
  486.         treatfirstline(retour,rcvd);
  487.  
  488. #if HDEBUG
  489.         printf("Status-Code=%d\n",retour->statuscode);
  490. #endif
  491.         
  492.         // en-tΩte
  493.         
  494.         // header // ** !attention! HTTP/0.9 non supportΘ
  495.         do {
  496.           finput(soc,rcvd,1024);          
  497. #if HDEBUG
  498.           printf(">%s\n",rcvd);      
  499. #endif
  500.           if (strnotempty(rcvd))
  501.             treathead(NULL,NULL,NULL,retour,rcvd);  // traiter
  502.  
  503.         } while(strnotempty(rcvd));
  504.         
  505.         //rcvsize=-1;    // forCER CHARGEMENT INCONNU
  506.         
  507.         //if (retour)
  508.         //  retour->totalsize=rcvsize;
  509.         
  510.       } else { // si GET, on recevra l'en tΩte APRES
  511.         //rcvsize=-1;    // on ne connait pas la taille de l'en-tΩte
  512.         if (retour)
  513.           retour->totalsize=-1;
  514.       }
  515.       
  516.     }
  517.  
  518.   }
  519.     
  520.   return soc;
  521. }
  522.  
  523.  
  524. // envoi d'une requΦte
  525. int http_sendhead(t_cookie* cookie,int mode,char* xsend,char* adr,char* fil,char* referer_adr,char* referer_fil,htsblk* retour) {
  526.   char buff[8192];
  527.   //int use_11=0;     // HTTP 1.1 utilisΘ
  528.   int direct_url=0; // ne pas analyser l'url (exemple: ftp://)
  529.   char* search_tag=NULL;
  530.   buff[0]='\0';
  531.  
  532.   // header Date
  533.   //strcat(buff,"Date: ");
  534.   //time_gmt_rfc822(buff);    // obtenir l'heure au format rfc822
  535.   //sendc("\n");
  536.   //strcat(buff,buff);
  537.  
  538.   // possibilitΘ non documentΘe: >post: et >postfile:
  539.   // si prΘsence d'un tag >post: alors executer un POST
  540.   // exemple: http://www.someweb.com/test.cgi?foo>post:posteddata=10&foo=5
  541.   // si prΘsence d'un tag >postfile: alors envoyer en tΩte brut contenu dans le fichier en question
  542.   // exemple: http://www.someweb.com/test.cgi?foo>postfile:post0.txt
  543.   search_tag=strstr(fil,POSTTOK":");
  544.   if (!search_tag) {
  545.     search_tag=strstr(fil,POSTTOK"file:");
  546.     if (search_tag) {     // postfile
  547.       if (mode==0) {      // GET!
  548.         FILE* fp=fopen(unescape_http(search_tag+strlen(POSTTOK)+5),"rb");
  549.         if (fp) {
  550.           char line[1100];
  551.           char protocol[256],url[HTS_URLMAXSIZE*2],method[256];
  552.           linput(fp,line,1000);
  553.           if (sscanf(line,"%s %s %s",method,url,protocol) == 3) {
  554.             // selon que l'on a ou pas un proxy
  555.             if (retour->req.proxy.active)
  556.               sprintf(buff,"%s http://%s%s %s\r\n",method,adr,url,protocol);
  557.             else
  558.               sprintf(buff,"%s %s %s\r\n",method,url,protocol);
  559.             // lire le reste en brut
  560.             fread(buff+strlen(buff),8000-strlen(buff),1,fp);
  561.           }
  562.           fclose(fp);
  563.         }
  564.       }
  565.     }
  566.   }
  567.   // Fin postfile
  568.   
  569.   if (strnotempty(buff)==0) {    // PAS POSTFILE
  570.     // Type de requΦte?
  571.     if ((search_tag) && (mode==0)) {
  572.       strcat(buff,"POST ");
  573.     } else if (mode==0) {    // GET
  574.       strcat(buff,"GET ");
  575.     } else {  // if (mode==1) {
  576.       if (!retour->req.http11)        // forcer HTTP/1.0
  577.         strcat(buff,"GET ");      // certains serveurs (cgi) buggent avec HEAD
  578.       else
  579.         strcat(buff,"HEAD ");
  580.     }
  581.     
  582.     // si on gΦre un proxy, il faut une Absolute URI: on ajoute avant http://www.adr.dom
  583.     if (retour->req.proxy.active) {
  584.       if (strncmp(adr,"ftp://",6)!=0) {
  585. #if HDEBUG
  586.         printf("Proxy Use: for %s%s proxy %d port %d\n",adr,fil,retour->req.proxy.name,retour->req.proxy.port);
  587. #endif
  588.         strcat(buff,"http://");
  589.         strcat(buff,jump_identification(adr));
  590.       } else {          // ftp:// en proxy http
  591. #if HDEBUG
  592.         printf("Proxy Use for ftp: for %s%s proxy %d port %d\n",adr,fil,retour->req.proxy.name,retour->req.proxy.port);
  593. #endif
  594.         direct_url=1;             // ne pas analyser user/pass
  595.         strcat(buff,adr);
  596.       }
  597.     } 
  598.     
  599.     // NOM DU FICHIER
  600.     // on slash doit Ωtre prΘsent en dΘbut, sinon attention aux bad request! (400)
  601.     if (*fil!='/') strcat(buff,"/");
  602.     {
  603.       char tempo[HTS_URLMAXSIZE*2];
  604.       tempo[0]='\0';
  605.       if (search_tag)
  606.         strncat(tempo,fil,(int) search_tag -(int) fil);
  607.       else
  608.         strcpy(tempo,fil);
  609.       escape_check_url(tempo);
  610.       strcat(buff,tempo);       // avec Θchappement
  611.     }
  612.     
  613.     // protocole
  614.     if (!retour->req.http11) {     // forcer HTTP/1.0
  615.       //use_11=0;
  616.       strcat(buff," HTTP/1.0\x0d\x0a");
  617.     } else {                   // RequΦte 1.1
  618.       //use_11=1;
  619.       strcat(buff," HTTP/1.1\x0d\x0a");
  620.     }
  621.  
  622.     /* supplemental data */
  623.     if (xsend) strcat(buff,xsend);    // Θventuelles autres lignes
  624.  
  625.     // tester proxy authentication
  626.     if (retour->req.proxy.active) {
  627.       char* a=jump_identification(retour->req.proxy.name);
  628.       if (a!=retour->req.proxy.name) {  // et hop, authentification proxy!
  629.         char autorisation[1100];
  630.         char user_pass[256];        
  631.         autorisation[0]=user_pass[0]='\0';
  632.         //
  633.         strncat(user_pass,retour->req.proxy.name,(int) a - (int) retour->req.proxy.name - 1);
  634.         strcpy(user_pass,unescape_http(user_pass));
  635.         code64(user_pass,autorisation);
  636.         strcat(buff,"Proxy-Authorization: Basic ");
  637.         strcat(buff,autorisation);
  638.         strcat(buff,H_CRLF);
  639. #if HDEBUG
  640.         printf("Proxy-Authenticate, %s (code: %s)\n",user_pass,autorisation);
  641. #endif
  642.       }
  643.     }
  644.     
  645.     // Referer?
  646.     if ((referer_adr) && (referer_fil)) {       // existe
  647.       if ((strnotempty(referer_adr)) && (strnotempty(referer_fil))) {   // non vide
  648.         if (strcmp(referer_adr,"file://")) {      // PAS file://
  649.           strcat(buff,"Referer: ");
  650.           strcat(buff,"http://");
  651.           strcat(buff,referer_adr);
  652.           strcat(buff,referer_fil);
  653.           strcat(buff,H_CRLF);
  654.         }
  655.       }
  656.     }
  657.     
  658.     // POST?
  659.     if (mode==0) {      // GET!
  660.       if (search_tag) {
  661.         char clen[256];
  662.         sprintf(clen,"Content-length: %d"H_CRLF,strlen(unescape_http(search_tag+strlen(POSTTOK)+1)));
  663.         strcat(buff,clen);
  664.       }
  665.     }
  666.     
  667.     // gestion cookies?
  668.     if (cookie) {
  669.       char* b=cookie->data;
  670.       int cook=0;
  671.       int max_cookies=8;
  672.       int max_size=2048;
  673.       max_size+=strlen(buff);
  674.       do {
  675.         b=cookie_find(b,"",jump_identification(adr),fil);       // prochain cookie satisfaisant aux conditions
  676.         if (b) {
  677.           max_cookies--;
  678.           if (!cook) {
  679.             strcat(buff,"Cookie: ");
  680.             strcat(buff,"$Version=1; ");
  681.             cook=1;
  682.           } else
  683.             strcat(buff,"; ");
  684.           strcat(buff,cookie_get(b,5));
  685.           strcat(buff,"=");
  686.           strcat(buff,cookie_get(b,6));
  687.           strcat(buff,"; $Path=");
  688.           strcat(buff,cookie_get(b,2));
  689.           b=cookie_nextfield(b);
  690.         }
  691.       } while( (b) && (max_cookies>0) && ((int)strlen(buff)<max_size));
  692.       if (cook) {                           // on a envoyΘ un (ou plusieurs) cookie?
  693.         strcat(buff,H_CRLF);
  694. #if DEBUG_COOK
  695.         printf("Header:\n%s\n",buff);
  696. #endif
  697.       }
  698.     }
  699.     
  700.     // connection close?
  701.     //if (use_11)     // Si on envoie une requΦte 1.1, prΘciser qu'on ne veut pas de keep-alive!!
  702.     strcat(buff,"Connection: close"H_CRLF);
  703.     
  704.     //strcat(buff,"Referer: http://");ppp
  705.     //strcat(buff,adr); 
  706.     //strcat(buff,"\n");
  707.     
  708.     // gΘrer le keep-alive (garder socket)
  709.     //strcat(buff,"Connection: Keep-Alive\n");
  710.     
  711.     {
  712.       char* real_adr=jump_identification(adr);
  713.       //if ((use_11) || (retour->user_agent_send)) {   // Pour le 1.1 on utilise un Host:
  714.       if (!direct_url) {     // pas ftp:// par exemple
  715.         //if (!retour->req.proxy.active) {
  716.         strcat(buff,"Host: "); strcat(buff,real_adr); strcat(buff,H_CRLF);
  717.         //}
  718.       }
  719.       //}
  720.  
  721.       // PrΘsence d'un user-agent?
  722.       if (retour->req.user_agent_send) {  // ohh un user-agent
  723.         char s[256];
  724.         // HyperTextSeeker/"HTSVERSION
  725.         sprintf(s,"User-Agent: %s"H_CRLF,retour->req.user_agent);
  726.         strcat(buff,s);
  727.         
  728.         // pour les serveurs difficiles
  729.         strcat(buff,"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*"H_CRLF);
  730.         if (strnotempty(retour->req.lang_iso)) {
  731.           strcat(buff,"Accept-Language: "); strcat(buff,retour->req.lang_iso); strcat(buff,H_CRLF);
  732.         }
  733.         strcat(buff,"Accept-Charset: iso-8859-1, *"H_CRLF);   
  734.         strcat(buff,"Accept-Encoding: identity"H_CRLF);         /* no compression */
  735.       } else {
  736.         strcat(buff,"Accept: */*"H_CRLF);         // le minimum
  737.       }
  738.  
  739.       /* Authentification */
  740.       {
  741.         char autorisation[1100];
  742.         char* a;
  743.         autorisation[0]='\0';
  744.         if (real_adr != adr) {  // ohh une authentification!
  745.           if (!direct_url) {      // pas ftp:// par exemple
  746.             char user_pass[256];
  747.             user_pass[0]='\0';
  748.             strncat(user_pass,adr,(int) real_adr - (int) adr - 1);
  749.             strcpy(user_pass,unescape_http(user_pass));
  750.             code64(user_pass,autorisation);
  751.             if (strcmp(fil,"/robots.txt"))      /* pas robots.txt */
  752.               bauth_add(cookie,real_adr,fil,autorisation);
  753.           }
  754.         } else if ( (a=bauth_check(cookie,real_adr,fil)) )
  755.           strcpy(autorisation,a);
  756.         /* On a une autorisation a donner?  */
  757.         if (strnotempty(autorisation)) {
  758.           strcat(buff,"Authorization: Basic ");
  759.           strcat(buff,autorisation);
  760.           strcat(buff,H_CRLF);
  761.         }
  762.       }
  763.  
  764.     }
  765.     //strcat(buff,"Accept-Language: en\n");
  766.     //strcat(buff,"Accept-Charset: iso-8859-1,*,utf-8\n");
  767.     
  768.     // CRLF de fin d'en tΩte
  769.     strcat(buff,H_CRLF);
  770.     
  771.     // donnΘes complΘmentaires?
  772.     if (search_tag)
  773.     if (mode==0)      // GET!
  774.       strcat(buff,unescape_http(search_tag+strlen(POSTTOK)+1));
  775.   }
  776.   
  777. #if HDEBUG
  778. #endif
  779.   if (_DEBUG_HEAD) {
  780.     if (ioinfo) {
  781.       fprintf(ioinfo,"Out:\r\n%s\r\n",buff);
  782.       fflush(ioinfo);
  783.     }
  784.   }  // Fin test pas postfile
  785.   //
  786.  
  787.   // Envoi
  788.   if (sendc(retour->soc,buff)<0) {  // ERREUR, socket rompue?...
  789.   //if (sendc(retour->soc,buff) != strlen(buff)) {  // ERREUR, socket rompue?...
  790.     deletesoc(retour->soc);  // fermer tout de mΩme
  791.     // et tenter de reconnecter
  792.     
  793.     strcpy(retour->msg,"Broken pipe");
  794.     retour->soc=INVALID_SOCKET;
  795.     /* non, α cause du poll connect()
  796.     // si on avait une connexion proxy, tenter une connexion directe cette fois!
  797.     retour->proxy.active=0;
  798.     if (retour) {
  799.     soc=newhttp(adr,retour->msg,-1,1);
  800.     retour->soc=soc;
  801.     }
  802.     else {
  803.     soc=newhttp(adr,NULL,-1,1);   
  804.     }
  805.     
  806.       // reconnectΘ?
  807.       if (soc!=INVALID_SOCKET) {        
  808.       if (sendc(soc,buff)<0) {  // NAN MARCHE PAS
  809.       strcpy(retour->msg,"Can not write to a re-established socket connexion");
  810.       deletesoc(soc);  // fermer tout de mΩme
  811.       soc=INVALID_SOCKET;
  812.       }
  813.       
  814.         } else {
  815.         strcpy(retour->msg,"Can not re-establish a socket connexion");
  816.         }
  817.     */
  818.   }
  819.   
  820.   // RX'98
  821.   return 0;
  822. }
  823.  
  824.  
  825.  
  826.  
  827. // traiter 1ere ligne d'en tΩte
  828. void treatfirstline(htsblk* retour,char* rcvd) {
  829.   char* a=rcvd;
  830.   // exemple:
  831.   // HTTP/1.0 200 OK
  832.   if (*a) {
  833.     // note: certains serveurs buggΘs renvoient HTTP/1.0\n200 OK ou " HTTP/1.0 200 OK"
  834.     while ((*a==' ') || (*a==10) || (*a==13) || (*a==9)) a++;      // Θpurer espaces au dΘbut
  835.     // sauter HTTP/1.x
  836.     while ((*a!=' ') && (*a!='\0') && (*a!=10) && (*a!=13) && (*a!=9)) a++;   
  837.     if (*a != '\0') {
  838.       while ((*a==' ') || (*a==10) || (*a==13) || (*a==9)) a++;      // Θpurer espaces
  839.       if ((*a>='0') && (*a<='9')) {
  840.         sscanf(a,"%d",&(retour->statuscode));
  841.         // sauter 200
  842.         while ((*a!=' ') && (*a!='\0') && (*a!=10) && (*a!=13) && (*a!=9)) a++;   
  843.         while ((*a==' ') || (*a==10) || (*a==13) || (*a==9)) a++;      // Θpurer espaces
  844.         if ((strlen(a) > 1) && (strlen(a) < 64) )                // message retour
  845.           strcpy(retour->msg,a);
  846.         else
  847.           infostatuscode(retour->msg,retour->statuscode);
  848.         // type MIME par dΘfaut
  849.         strcpy(retour->contenttype,HTS_HYPERTEXT_DEFAULT_MIME);
  850.       } else {  // pas de code!
  851.         retour->statuscode=-1;
  852.         strcpy(retour->msg,"Unknown response structure");
  853.       }
  854.     } else {  // euhh??
  855.       retour->statuscode=-1;
  856.       strcpy(retour->msg,"Unknown response structure");
  857.     }
  858.   } else {  // vide!
  859.     retour->statuscode=-1;
  860.     strcpy(retour->msg,"Empty reponse or internal error");
  861.   }
  862. }
  863.  
  864. // traiter ligne par ligne l'en tΩte
  865. // gestion des cookies
  866. void treathead(t_cookie* cookie,char* adr,char* fil,htsblk* retour,char* rcvd) {
  867.   int p;
  868.   if ((p=strfield(rcvd,"Content-length:"))!=0) {
  869. #if HDEBUG
  870.     printf("ok, Content-length: dΘtectΘ\n");
  871. #endif
  872.     sscanf(rcvd+p,LLintP,&(retour->totalsize));
  873.   }
  874.   else if ((p=strfield(rcvd,"Content-Disposition:"))!=0) {
  875.     while(*(rcvd+p)==' ') p++;    // sauter espaces
  876.     if ((int) strlen(rcvd+p)<250) { // pas trop long?
  877.       char tmp[256];
  878.       char *a=NULL,*b=NULL;
  879.       strcpy(tmp,rcvd+p);
  880.       a=strstr(tmp,"filename=");
  881.       if (a) {
  882.         a+=strlen("filename=");
  883.         while(is_space(*a)) a++;
  884.         //a=strchr(a,'"');
  885.         if (a) {
  886.           char *c=NULL;
  887.           //a++;      /* jump " */
  888.           while((c=strchr(a,'/')))    /* skip all / (see RFC2616) */
  889.             a=c+1;
  890.           //b=strchr(a+1,'"');
  891.           b=a+strlen(a)-1;
  892.           while(is_space(*b)) b--;
  893.           b++;
  894.           if (b) {
  895.             *b='\0';
  896.             if ((int) strlen(a) < 200) { // pas trop long?
  897.               strcpy(retour->cdispo,a);
  898.             }
  899.           }
  900.         }
  901.       } 
  902.     }
  903.   }
  904.   else if ((p=strfield(rcvd,"Last-Modified:"))!=0) {
  905.     while(*(rcvd+p)==' ') p++;    // sauter espaces
  906.     if ((int) strlen(rcvd+p)<64) { // pas trop long?
  907.       //struct tm* tm_time=convert_time_rfc822(rcvd+p);
  908.       strcpy(retour->lastmodified,rcvd+p);
  909.     }
  910.   }
  911.   else if ((p=strfield(rcvd,"Date:"))!=0) {
  912.     if (strnotempty(retour->lastmodified)==0) {          /* pas encore de last-modified */
  913.       while(*(rcvd+p)==' ') p++;    // sauter espaces
  914.       if ((int) strlen(rcvd+p)<64) { // pas trop long?
  915.         //struct tm* tm_time=convert_time_rfc822(rcvd+p);
  916.         strcpy(retour->lastmodified,rcvd+p);
  917.       }
  918.     }
  919.   }
  920.   else if ((p=strfield(rcvd,"Etag:"))!=0) {   /* Etag */
  921.     if (retour) {
  922.       while(*(rcvd+p)==' ') p++;    // sauter espaces
  923.       if ((int) strlen(rcvd+p)<64)  // pas trop long?
  924.         strcpy(retour->etag,rcvd+p);
  925.       else    // erreur.. ignorer
  926.         retour->etag[0]='\0';
  927.     }
  928.   }
  929.   else if ((p=strfield(rcvd,"Transfer-Encoding: chunked"))!=0) {  // chunk!
  930.     retour->is_chunk=1;     // chunked
  931.     //retour->http11=2;     // chunked
  932. #if HDEBUG
  933.     printf("ok, Transfer-Encoding: dΘtectΘ\n");
  934. #endif
  935.   }
  936.   else if ((p=strfield(rcvd,"Content-type:"))!=0) {
  937.     if (retour) {
  938.       char tempo[1100];
  939.       // Θviter les text/html; charset=foo
  940.       {
  941.         char* a=strchr(rcvd+p,';');
  942.         if (a) *a='\0';
  943.       }
  944.       sscanf(rcvd+p,"%s",tempo);
  945.       if (strlen(tempo)<64)    // pas trop long!!
  946.         strcpy(retour->contenttype,tempo);
  947.       else
  948.         strcpy(retour->contenttype,"application/octet-stream-unknown");    // erreur
  949.     }
  950.   }
  951.   else if ((p=strfield(rcvd,"Location:"))!=0) {
  952.     if (retour) {
  953.       if (retour->location) {
  954.         while(*(rcvd+p)==' ') p++;    // sauter espaces
  955.         if ((int) strlen(rcvd+p)<HTS_URLMAXSIZE)  // pas trop long?
  956.           sscanf(rcvd+p,"%s",retour->location);
  957.         else    // erreur.. ignorer
  958.           retour->location[0]='\0';
  959.       }
  960.     }
  961.   }
  962.   else if ((p=strfield(rcvd,"Connection: Keep-Alive"))!=0) {
  963.     // non, pas de keep-alive! on dΘconnectera..          
  964.   }
  965.   else if ((p=strfield(rcvd,"Keep-Alive:"))!=0) {    // params keep-alive
  966.     // rien α faire          
  967.   }
  968.   else if ( ((p=strfield(rcvd,"Set-Cookie:"))!=0) && (cookie) ) {    // ohh un cookie
  969.     char* a = rcvd+p;           // pointeur
  970.     char domain[256];           // domaine cookie (.netscape.com)
  971.     char path[256];             // chemin (/)
  972.     char cook_name[256];        // nom cookie (MYCOOK)
  973.     char cook_value[8192];      // valeur (ID=toto,S=1234)
  974. #if DEBUG_COOK
  975.     printf("set-cookie detected\n");
  976. #endif
  977.     while(*a) {
  978.       char *token_st,*token_end;
  979.       char *value_st,*value_end;
  980.       char name[256];
  981.       char value[8192];
  982.       int next=0;
  983.       name[0]=value[0]='\0';
  984.       //
  985.  
  986.       // initialiser cookie lu actuellement
  987.       if (adr)
  988.         strcpy(domain,jump_identification(adr));     // domaine
  989.       strcpy(path,"/");         // chemin (/)
  990.       strcpy(cook_name,"");     // nom cookie (MYCOOK)
  991.       strcpy(cook_value,"");    // valeur (ID=toto,S=1234)
  992.       // boucler jusqu'au prochain cookie ou la fin
  993.       do {
  994.         char* start_loop=a;
  995.         while(is_space(*a)) a++;    // sauter espaces
  996.         token_st=a;                 // dΘpart token
  997.         while((!is_space(*a)) && (*a) && (*a!=';') && (*a!='=')) a++;    // arrΩter si espace, point virgule
  998.         token_end=a;
  999.         while(is_space(*a)) a++;    // sauter espaces
  1000.         if (*a=='=') {    // name=value
  1001.           a++;
  1002.           while(is_space(*a)) a++;    // sauter espaces
  1003.           value_st=a;
  1004.           while( (*a!=';') && (*a)) a++;    // prochain ;
  1005.           //while( ((*a!='"') || (*(a-1)=='\\')) && (*a)) a++;    // prochain " (et pas \")
  1006.           value_end=a;
  1007.           //if (*a==';') {  // finit par un ;
  1008.           // vΘrifier dΘbordements
  1009.           if ( (((int) token_end - (int) token_st)<200) && (((int) value_end - (int) value_st)<8000)
  1010.             && (((int) token_end - (int) token_st)>0)   && (((int) value_end - (int) value_st)>0) ) {
  1011.             name[0]='\0';
  1012.             value[0]='\0';
  1013.             strncat(name,token_st,(int) token_end - (int) token_st);
  1014.             strncat(value,value_st,(int) value_end - (int) value_st);
  1015. #if DEBUG_COOK
  1016.             printf("detected cookie-av: name=\"%s\" value=\"%s\"\n",name,value);
  1017. #endif
  1018.             if (strfield2(name,"domain")) {
  1019.               strcpy(domain,value);
  1020.             }
  1021.             else if (strfield2(name,"path")) {
  1022.               strcpy(path,value);
  1023.             }
  1024.             else if (strfield2(name,"max-age")) {
  1025.               // ignorΘ..
  1026.             }
  1027.             else if (strfield2(name,"expires")) {
  1028.               // ignorΘ..
  1029.             }
  1030.             else if (strfield2(name,"version")) {
  1031.               // ignorΘ..
  1032.             }
  1033.             else if (strfield2(name,"comment")) {
  1034.               // ignorΘ
  1035.             }
  1036.             else if (strfield2(name,"secure")) {    // ne devrait pas arriver ici
  1037.               // ignorΘ
  1038.             }
  1039.             else {
  1040.               if (strnotempty(cook_name)==0) {          // noter premier: nom et valeur cookie
  1041.                 strcpy(cook_name,name);
  1042.                 strcpy(cook_value,value);
  1043.               } else {                             // prochain cookie
  1044.                 a=start_loop;      // on devra recommencer α cette position
  1045.                 next=1;            // enregistrer
  1046.               }
  1047.             }
  1048.           }
  1049.         }
  1050.         if (!next) {
  1051.           while((*a!=';') && (*a)) a++;    // prochain
  1052.           while(*a==';') a++;             // sauter ;
  1053.         }
  1054.       } while((*a) && (!next));
  1055.       if (strnotempty(cook_name)) {          // cookie?
  1056. #if DEBUG_COOK
  1057.         printf("new cookie: name=\"%s\" value=\"%s\" domain=\"%s\" path=\"%s\"\n",cook_name,cook_value,domain,path);
  1058. #endif
  1059.         cookie_add(cookie,cook_name,cook_value,domain,path);
  1060.       }
  1061.     }
  1062.   }
  1063. }
  1064.  
  1065.  
  1066. // transforme le message statuscode en chaεne
  1067. void infostatuscode(char* msg,int statuscode) {
  1068.   switch( statuscode) {    
  1069.     // Erreurs HTTP, selon RFC
  1070.   case 100: strcpy( msg,"Continue"); break; 
  1071.   case 101: strcpy( msg,"Switching Protocols"); break; 
  1072.   case 200: strcpy( msg,"OK"); break; 
  1073.   case 201: strcpy( msg,"Created"); break; 
  1074.   case 202: strcpy( msg,"Accepted"); break; 
  1075.   case 203: strcpy( msg,"Non-Authoritative Information"); break; 
  1076.   case 204: strcpy( msg,"No Content"); break; 
  1077.   case 205: strcpy( msg,"Reset Content"); break; 
  1078.   case 206: strcpy( msg,"Partial Content"); break; 
  1079.   case 300: strcpy( msg,"Multiple Choices"); break; 
  1080.   case 301: strcpy( msg,"Moved Permanently"); break; 
  1081.   case 302: strcpy( msg,"Moved Temporarily"); break; 
  1082.   case 303: strcpy( msg,"See Other"); break; 
  1083.   case 304: strcpy( msg,"Not Modified"); break; 
  1084.   case 305: strcpy( msg,"Use Proxy"); break; 
  1085.   case 306: strcpy( msg,"Undefined 306 error"); break; 
  1086.   case 307: strcpy( msg,"Temporary Redirect"); break; 
  1087.   case 400: strcpy( msg,"Bad Request"); break; 
  1088.   case 401: strcpy( msg,"Unauthorized"); break; 
  1089.   case 402: strcpy( msg,"Payment Required"); break; 
  1090.   case 403: strcpy( msg,"Forbidden"); break; 
  1091.   case 404: strcpy( msg,"Not Found"); break; 
  1092.   case 405: strcpy( msg,"Method Not Allowed"); break; 
  1093.   case 406: strcpy( msg,"Not Acceptable"); break; 
  1094.   case 407: strcpy( msg,"Proxy Authentication Required"); break; 
  1095.   case 408: strcpy( msg,"Request Time-out"); break; 
  1096.   case 409: strcpy( msg,"Conflict"); break; 
  1097.   case 410: strcpy( msg,"Gone"); break; 
  1098.   case 411: strcpy( msg,"Length Required"); break; 
  1099.   case 412: strcpy( msg,"Precondition Failed"); break; 
  1100.   case 413: strcpy( msg,"Request Entity Too Large"); break; 
  1101.   case 414: strcpy( msg,"Request-URI Too Large"); break; 
  1102.   case 415: strcpy( msg,"Unsupported Media Type"); break; 
  1103.   case 416: strcpy( msg,"Requested Range Not Satisfiable"); break; 
  1104.   case 417: strcpy( msg,"Expectation Failed"); break; 
  1105.   case 500: strcpy( msg,"Internal Server Error"); break; 
  1106.   case 501: strcpy( msg,"Not Implemented"); break; 
  1107.   case 502: strcpy( msg,"Bad Gateway"); break; 
  1108.   case 503: strcpy( msg,"Service Unavailable"); break; 
  1109.   case 504: strcpy( msg,"Gateway Time-out"); break; 
  1110.   case 505: strcpy( msg,"HTTP Version Not Supported"); break; 
  1111.     //
  1112.   default: if (strnotempty(msg)==0) strcpy( msg,"Unknown error"); break;
  1113.   }
  1114. }
  1115.  
  1116.  
  1117. // identique au prΘcΘdent, sauf que l'on donne adr+fil et non url complΦte
  1118. htsblk xhttpget(char* adr,char* fil) {
  1119.   T_SOC soc;
  1120.   htsblk retour;
  1121.   
  1122.   bzero((char *)&retour, sizeof(htsblk));
  1123.   soc=http_fopen(adr,fil,&retour);
  1124.  
  1125.   if (soc!=INVALID_SOCKET) {
  1126.     http_fread(soc,&retour);
  1127. #if HTS_DEBUG_CLOSESOCK
  1128.     DEBUG_W("xhttpget: deletehttp\n");
  1129. #endif
  1130.     if (retour.soc!=INVALID_SOCKET) deletehttp(&retour);  // fermer
  1131.     retour.soc=INVALID_SOCKET;
  1132.   }
  1133.   return retour;
  1134. }
  1135.  
  1136. // variation sur un thΦme...
  1137. // rΘceptionne uniquement un en-tΩte (HEAD)
  1138. // retourne dans xx.adr l'adresse pointant sur le bloc de mΘmoire de l'en tΩte
  1139. htsblk http_gethead(char* adr,char* fil) {
  1140.   T_SOC soc;
  1141.   htsblk retour;
  1142.  
  1143.   bzero((char *)&retour, sizeof(htsblk));
  1144.   soc=http_xfopen(1,0,1,NULL,adr,fil,&retour);  // HEAD, pas de traitement en-tΩte
  1145.  
  1146.   if (soc!=INVALID_SOCKET) {
  1147.     http_fread(soc,&retour);    // rΘception en-tΩte
  1148. #if HTS_DEBUG_CLOSESOCK
  1149.     DEBUG_W("http_gethead: deletehttp\n");
  1150. #endif
  1151.     if (retour.soc!=INVALID_SOCKET) deletehttp(&retour);  // fermer
  1152.     retour.soc=INVALID_SOCKET;
  1153.   }
  1154.   return retour;
  1155. }
  1156. // oui ca ressemble vachement α xhttpget - en Θtant sobre on peut voir LA diffΘrence..
  1157.  
  1158.  
  1159. // lecture sur une socket ouverte, le header a dΘja ΘtΘ envoyΘ dans le cas de GET
  1160. // il ne reste plus qu'α lire les donnΘes
  1161. // (pour HEAD le header est lu ici!)
  1162. void http_fread(T_SOC soc,htsblk* retour) {  
  1163.   //int bufl=TAILLE_BUFFER;    // 8Ko de buffer
  1164.   
  1165.   if (retour) retour->soc=soc;
  1166.   if (soc!=INVALID_SOCKET) {    
  1167.     // fonction de lecture d'une socket (plus propre)
  1168.     while(http_fread1(retour)!=-1);
  1169.     soc=retour->soc;
  1170.     if (retour->adr==NULL) {
  1171.       if (strnotempty(retour->msg)==0)
  1172.         sprintf(retour->msg,"Unable to read");
  1173.       return ;    // erreur
  1174.     } 
  1175.     
  1176. #if HDEBUG
  1177.     printf("Ok, donnΘes reτues\n");
  1178. #endif   
  1179.  
  1180.     return ;
  1181.     
  1182.   } 
  1183.   
  1184.   return ;
  1185. }
  1186.  
  1187. // lecture d'un bloc sur une socket (ou un fichier!)
  1188. HTS_INLINE LLint http_fread1(htsblk* r) {
  1189.   //int bufl=TAILLE_BUFFER;  // taille d'un buffer max.
  1190.   return http_xfread1(r,TAILLE_BUFFER);
  1191. }
  1192.  
  1193. // idem, sauf qu'ici on peut choisir la taille max de donnΘes α recevoir
  1194. // SI bufl=0 alors le buffer est censΘ Ωtre de 8kos, et on recoit caractΦres
  1195. // par caractΦres en Θliminant les cr (ex: header)
  1196. // Note: les +1 dans les malloc sont d√s α l'octet nul rajoutΘ en fin de fichier
  1197. LLint http_xfread1(htsblk* r,int bufl) {
  1198.   int nl=-1;
  1199.  
  1200.   if (bufl>0) {
  1201.     if (!r->is_write) {     // stocker en mΘmoire
  1202.       if (r->totalsize>0) {    // totalsize dΘterminΘ ET ALLOUE
  1203.         if (r->adr==NULL) {
  1204.           r->adr=(char*) malloct((INTsys) r->totalsize + 1);
  1205.           r->size=0;
  1206.         }
  1207.         if (r->adr!=NULL) {
  1208.           // lecture
  1209.           nl=hts_read(r,r->adr + ((int) r->size),(int) (r->totalsize-r->size) );     /* NO 32 bit overlow possible here (no 4GB html!) */
  1210.           // nouvelle taille
  1211.           if (nl>0) r->size+=nl;
  1212.           
  1213.           if ((nl<=0) || (r->size >= r->totalsize))
  1214.             nl=-1;  // break
  1215.           
  1216.           r->adr[r->size]='\0';    // caractΦre NULL en fin au cas o∙ l'on traite des HTML
  1217.         }
  1218.         
  1219.       } else {                 // inconnu..
  1220.         // rΘserver de la mΘmoire?
  1221.         if (r->adr==NULL) {
  1222. #if HDEBUG
  1223.           printf("..alloc xfread\n");
  1224. #endif
  1225.           r->adr=(char*) malloct(bufl + 1);
  1226.           r->size=0;
  1227.         }
  1228.         else {
  1229. #if HDEBUG
  1230.           printf("..realloc xfread1\n");
  1231. #endif
  1232.           r->adr=(char*) realloct(r->adr,(int)r->size+bufl + 1);
  1233.         }
  1234.         
  1235.         if (r->adr!=NULL) {
  1236.           // lecture
  1237.           nl=hts_read(r,r->adr+(int)r->size,bufl);
  1238.           if (nl>0) {
  1239.             // resize
  1240.             r->adr=(char*) realloct(r->adr,(int)r->size+nl + 1);
  1241.             // nouvelle taille
  1242.             if (nl>0) r->size+=nl;
  1243.  
  1244.             if (r->adr) r->adr[r->size]='\0';    // octet nul
  1245.  
  1246.           } // sinon on a fini
  1247. #if HDEBUG
  1248.           else
  1249.             printf("..end read (%d)\n",nl);
  1250. #endif
  1251.         }
  1252. #if HDEBUG
  1253.         else printf("..-> error\n");
  1254. #endif
  1255.       }
  1256.  
  1257.       // pas de adr=erreur
  1258.       if (r->adr==NULL) nl=-1;
  1259.  
  1260.     } else {    // stocker sur disque
  1261.       char* buff;
  1262.       buff=(char*) malloct(bufl);
  1263.       if (buff!=NULL) {
  1264.         // lecture
  1265.         nl=hts_read(r,buff,bufl);
  1266.         // nouvelle taille
  1267.         if (nl>0) { 
  1268.           r->size+=nl;
  1269.           if ((int) fwrite(buff,1,nl,r->out)!=nl) {
  1270.             r->statuscode=-1;
  1271.             strcpy(r->msg,"Write error on disk");
  1272.             nl=-1;
  1273.           }
  1274.         }
  1275.  
  1276.         if ((nl<=0) || ((r->totalsize>0) && (r->size >= r->totalsize)))
  1277.           nl=-1;  // break
  1278.  
  1279.         // libΘrer bloc tempo
  1280.         freet(buff);
  1281.       } else nl=-1;
  1282.       
  1283.       // NON ce n'est pas notre r⌠le - et cela pose des problΦmes pour la rΘception en chunk
  1284.       /*
  1285.         //if (nl<=0)    // fin
  1286.         //if (r->out!=NULL) { fclose(r->out); r->out=NULL; }
  1287.       */
  1288.       if (nl<=0)    // fin
  1289.       if (r->out!=NULL) { fflush(r->out); }
  1290.         
  1291.         
  1292.     } // stockage disque ou mΘmoire
  1293.  
  1294.   } else {    // rΘception d'un en-tΩte octet par octet
  1295.  
  1296.     if (r->adr==NULL) {
  1297.       r->adr=(char*) malloct(8192);
  1298.       r->size=0;
  1299.     }
  1300.     
  1301.     if (r->adr!=NULL) {
  1302.       // lecture
  1303.       nl=hts_read(r,r->adr+r->size,1);
  1304.       if (nl>0) {
  1305.         if (*(r->adr+r->size) != 13)    // sauter caractΦres 13
  1306.           (r->size)++;
  1307.         *(r->adr+r->size)='\0';    // terminer par octet nul
  1308.       }
  1309.       if (r->size>=8190) {
  1310.         nl=-1;    // break
  1311.       }
  1312.     }
  1313.     // pas de adr=erreur
  1314.     if (r->adr==NULL) nl=-1;
  1315.   }
  1316. #if HDEBUG
  1317.   //printf("add to %d / %d\n",r->size,r->totalsize);
  1318. #endif
  1319.   return ((nl>0)?0:-1);
  1320. }
  1321.  
  1322.  
  1323. // teste une adresse, et suit l'Θventuel chemin "moved"
  1324. // retourne 200 ou le code d'erreur (404=NOT FOUND, etc)
  1325. // copie dans loc la vΘritable adresse si celle-ci est diffΘrente
  1326. htsblk http_location(char* adr,char* fil,char* loc) {
  1327.   htsblk retour;
  1328.   int retry=0;
  1329.   int tryagain;
  1330.   // note: "RFC says"
  1331.   // 5 boucles au plus, on en teste au plus 8 ici
  1332.   // sinon abandon..
  1333.   do {
  1334.     tryagain=0;
  1335.     switch ((retour=http_test(adr,fil,loc)).statuscode) {
  1336.     case 200: break;   // ok!
  1337.     case 301: case 302: case 303: case 307: // moved!
  1338.       // recalculer adr et fil!
  1339.       if (ident_url(loc,adr,fil)!=-1) {
  1340.         tryagain=1;  // retenter
  1341.         retry++;     // ..encore une fois
  1342.       }
  1343.     }
  1344.   } while((tryagain) && (retry<5+3));
  1345.   return retour;
  1346. }
  1347.  
  1348.  
  1349. // teste si une URL (validitΘ, header, taille)
  1350. // retourne 200 ou le code d'erreur (404=NOT FOUND, etc)
  1351. // en cas de moved xx, dans location
  1352. // abandonne dΘsormais au bout de 30 secondes (aurevoir les sites
  1353. // qui nous font poireauter 5 heures..) -> -2=timeout
  1354. htsblk http_test(char* adr,char* fil,char* loc) {
  1355.   T_SOC soc;
  1356.   htsblk retour;
  1357.   //int rcvsize=-1;
  1358.   //char* rcv=NULL;    // adresse de retour
  1359.   //int bufl=TAILLE_BUFFER;    // 8Ko de buffer
  1360.   double tl;
  1361.   int timeout=30;  // timeout pour un check (arbitraire) // **
  1362.  
  1363.   // pour abandonner un site trop lent
  1364.   tl=time_local();
  1365.  
  1366.   loc[0]='\0';
  1367.   bzero((char *)&retour, sizeof(htsblk));    // effacer
  1368.   retour.location=loc;    // si non nul, contiendra l'adresse vΘritable en cas de moved xx
  1369.  
  1370.   //soc=http_fopen(adr,fil,&retour,NULL);  // ouvrir, + header
  1371.  
  1372.   // on ouvre en head, et on traite l'en tΩte
  1373.   soc=http_xfopen(1,0,1,NULL,adr,fil,&retour);  // ouvrir HEAD, + envoi header
  1374.   
  1375.   if (soc!=INVALID_SOCKET) {
  1376.     int e=0;
  1377.     // tant qu'on a des donnΘes, et qu'on ne recoit pas deux LF, et que le timeout n'arrie pas
  1378.     do {
  1379.       if (http_xfread1(&retour,0)==-1)
  1380.         e=1;
  1381.       else {
  1382.         if (retour.adr!=NULL) {
  1383.           if ((retour.adr[retour.size-1]!=10) || (retour.adr[retour.size-2]!=10))
  1384.             e=1;
  1385.         }
  1386.       }
  1387.             
  1388.       if (!e) {
  1389.         if ((time_local()-tl)>=timeout) {
  1390.           e=-1;
  1391.         }
  1392.       }
  1393.       
  1394.     } while (!e);
  1395.     
  1396.     if (e==1) {
  1397.       if (adr!=NULL) {
  1398.         int ptr=0;
  1399.         char rcvd[1100];
  1400.  
  1401.         // note: en gros recopie du traitement de back_wait()
  1402.         //
  1403.  
  1404.  
  1405.         // ----------------------------------------
  1406.         // traiter en-tΩte!
  1407.         // status-line α rΘcupΘrer
  1408.         ptr+=binput(retour.adr+ptr,rcvd,1024);
  1409.         if (strnotempty(rcvd)==0)
  1410.           ptr+=binput(retour.adr+ptr,rcvd,1024);    // "certains serveurs buggΘs envoient un \n au dΘbut" (RFC)
  1411.         
  1412.         // traiter status-line
  1413.         treatfirstline(&retour,rcvd);
  1414.         
  1415. #if HDEBUG
  1416.         printf("(Buffer) Status-Code=%d\n",retour.statuscode);
  1417. #endif
  1418.         
  1419.         // en-tΩte
  1420.         
  1421.         // header // ** !attention! HTTP/0.9 non supportΘ
  1422.         do {
  1423.           ptr+=binput(retour.adr+ptr,rcvd,1024);          
  1424. #if HDEBUG
  1425.           printf("(buffer)>%s\n",rcvd);      
  1426. #endif
  1427.           if (strnotempty(rcvd))
  1428.             treathead(NULL,NULL,NULL,&retour,rcvd);  // traiter
  1429.           
  1430.         } while(strnotempty(rcvd));
  1431.         // ----------------------------------------                    
  1432.         
  1433.         // libΘrer mΘmoire
  1434.         if (retour.adr!=NULL) { freet(retour.adr); retour.adr=NULL; }
  1435.       }
  1436.     } else {
  1437.       retour.statuscode=-2;
  1438.       strcpy(retour.msg,"Timeout While Testing");
  1439.     }
  1440.     
  1441.     
  1442. #if HTS_DEBUG_CLOSESOCK
  1443.     DEBUG_W("http_test: deletehttp\n");
  1444. #endif
  1445.     deletehttp(&retour);
  1446.     retour.soc=INVALID_SOCKET;
  1447.   }
  1448.   return retour;    
  1449. }
  1450.  
  1451. // CrΘe un lien (http) vers une adresse internet iadr
  1452. // retour: structure (adresse, taille, message si erreur (si !adr))
  1453. // peut ouvrir avec des connect() non bloquants: waitconnect=0/1
  1454. int newhttp(char* _iadr,htsblk* retour,int port,int waitconnect) {  
  1455.   T_SOC soc;                           // descipteur de la socket
  1456.   char* iadr;
  1457.   // unsigned short int port;
  1458.   
  1459.   // tester un Θventuel id:pass et virer id:pass@ si dΘtectΘ
  1460.   iadr = jump_identification(_iadr);
  1461.   
  1462.   // si iadr="#" alors c'est une fausse URL, mais un vrai fichier
  1463.   // local.
  1464.   // utile pour les tests!
  1465.   //## if (iadr[0]!=lOCAL_CHAR) {
  1466.   if (strcmp(iadr,"file://")) {           /* non fichier */
  1467.     struct sockaddr_in server;
  1468.     t_hostent* hp;    
  1469.     // effacer structure
  1470.     bzero((char *)&server, sizeof(server));
  1471.  
  1472. #if HDEBUG
  1473.     printf("gethostbyname\n");
  1474. #endif
  1475.     
  1476.     // tester un Θventuel port
  1477.     if (port==-1) {
  1478.       char *a=strchr(iadr,':');
  1479.       port=80;    // port par dΘfaut
  1480.       if (a) {
  1481.         char iadr2[HTS_URLMAXSIZE*2];
  1482.         int i=-1;
  1483.         iadr2[0]='\0';
  1484.         sscanf(a+1,"%d",&i);
  1485.         if (i!=-1) {
  1486.           port=(unsigned short int) i;
  1487.         }
  1488.         
  1489.         // adresse vΘritable (sans :xx)
  1490.         strncat(iadr2,iadr,(int) a-(int) iadr);
  1491.  
  1492.         // adresse sans le :xx
  1493.         hp = hts_gethostbyname(iadr2);
  1494.         
  1495.       } else {
  1496.  
  1497.         // adresse normale (port par dΘfaut par la suite)
  1498.         hp = hts_gethostbyname(iadr);
  1499.         
  1500.       }
  1501.       
  1502.     } else    // port dΘfini
  1503.       hp = hts_gethostbyname(iadr);
  1504.  
  1505.     
  1506.     // Conversion iadr -> adresse
  1507.     // structure recevant le nom de l'h⌠te, etc
  1508.     //struct     hostent     *hp;
  1509.     if (hp == NULL) {
  1510. #if DEBUG
  1511.       printf("erreur gethostbyname\n");
  1512. #endif
  1513.       if (retour)
  1514.       if (retour->msg)
  1515.         strcpy(retour->msg,"Unable to get server's address");
  1516.       return INVALID_SOCKET;
  1517.     }  
  1518.     // copie adresse
  1519.     bcopy(hp->h_addr, (char *)&server.sin_addr, hp->h_length);
  1520.  
  1521.     
  1522.     // crΘer ("attachement") une socket (point d'accΦs) internet,en flot
  1523. #if HDEBUG
  1524.     printf("socket\n");
  1525. #endif
  1526. #if HTS_WIDE_DEBUG    
  1527.     DEBUG_W("socket\n");
  1528. #endif
  1529.     soc=socket(AF_INET,SOCK_STREAM,0);
  1530. #if HTS_WIDE_DEBUG    
  1531.     DEBUG_W("socket done\n");
  1532. #endif
  1533.     if (soc==INVALID_SOCKET) {
  1534.       if (retour)
  1535.       if (retour->msg)
  1536.         strcpy(retour->msg,"Unable to create a socket");
  1537.       return INVALID_SOCKET;                        // erreur crΘation socket impossible
  1538.     }
  1539.     // structure: connexion au domaine internet, port 80 (ou autre)
  1540.     server.sin_family = AF_INET;
  1541.     server.sin_port = htons((unsigned short int) port);
  1542. #if HDEBUG
  1543.     printf("==%d\n",soc);
  1544. #endif
  1545.  
  1546.     // connexion non bloquante?
  1547.     if (!waitconnect ) {
  1548.       unsigned long p=1;  // non bloquant
  1549. #if HTS_WIN
  1550.       ioctlsocket(soc,FIONBIO,&p);
  1551. #else
  1552.       ioctl(soc,FIONBIO,&p);
  1553. #endif
  1554.     }
  1555.     
  1556.     // Connexion au serveur lui mΩme
  1557. #if HDEBUG
  1558.     printf("connect\n");
  1559. #endif
  1560.     
  1561. #if HTS_WIDE_DEBUG
  1562.     DEBUG_W("connect\n");
  1563. #endif
  1564. #if HTS_WIN
  1565.     if (connect(soc, (const struct sockaddr FAR *)&server, sizeof(server)) != 0) {
  1566. #else
  1567.       if (connect(soc, (struct sockaddr *)&server, sizeof(server)) == -1) {
  1568. #endif
  1569.         // bloquant
  1570.         if (waitconnect) {
  1571. #if HDEBUG
  1572.           printf("unable to connect!\n");
  1573. #endif
  1574.           if (retour)
  1575.           if (retour->msg)
  1576.             strcpy(retour->msg,"Unable to connect to the server");
  1577.           deletesoc(soc);
  1578.           return INVALID_SOCKET;
  1579.         }
  1580.       }
  1581. #if HTS_WIDE_DEBUG    
  1582.       DEBUG_W("connect done\n");
  1583. #endif
  1584.       
  1585. #if HDEBUG
  1586.       printf("connexion Θtablie\n");
  1587. #endif
  1588.     
  1589.     // A partir de maintenant, on peut envoyer et recevoir des donnΘes
  1590.     // via le flot identifiΘ par soc (socket): write(soc,adr,taille) et 
  1591.     // read(soc,adr,taille)
  1592.  
  1593.   } else {    // on doit ouvrir un fichier local!
  1594.     // il sera gΘrΘ de la mΩme maniΦre qu'une socket (c'est idem!)
  1595.  
  1596.     soc=LOCAL_SOCKET_ID;    // pseudo-socket locale..
  1597.     // soc sera remplacΘ lors d'un http_fopen() par un handle vΘritable!
  1598.  
  1599.   }   // teste fichier local ou http
  1600.   
  1601.   return soc;
  1602. }
  1603.  
  1604.  
  1605.  
  1606. // couper http://www.truc.fr/pub/index.html -> www.truc.fr /pub/index.html
  1607. // retour=-1 si erreur.
  1608. // si file://... alors adresse=file:// (et coupe le ?query dans ce cas)
  1609. int ident_url(char* url,char* adr,char* fil) {
  1610.   char *p,*q;
  1611.   // traiter url
  1612.  
  1613.   // effacer adr et fil
  1614.   adr[0]=fil[0]='\0';
  1615.   
  1616.   p=strstr(url,"://");    // "scheme":// (RFC1945)
  1617.   if (p) {
  1618. #if HDEBUG
  1619.     printf("protocol: %s\n",url);
  1620. #endif
  1621.     // analyser le scheme
  1622.     if (strfield(url,"mailto")!=0) {
  1623.       return -1;    // erreur non reconnu
  1624.     } else if (strfield(url,"news")!=0) {
  1625.       return -1;    // erreur non reconnu
  1626.     } else if (strfield(url,"javascript")!=0) {
  1627.       return -1;    // erreur non reconnu
  1628.     //
  1629.     } else if (strfield(url,"file")!=0) {    // fichier local!! (pour les tests)
  1630.       p+=3;
  1631.       strcpy(adr,"file://");
  1632.       //## strcpy(adr,lOCAL_CHAR_STR);    // indique un fichier local..
  1633.     //
  1634.     } else if (strfield(url,"http")!=0) {    // HTTP
  1635.       p+=3;
  1636.     //
  1637.     } else if (strfield(url,"ftp")!=0) {    // FTP
  1638.       //if (ftp_available()) {
  1639.       strcpy(adr,"ftp://");    // FTP!!
  1640.       //}
  1641.       p+=3;
  1642.     } else {
  1643.       // return -1;
  1644.       p+=3;    // tant pis, beaucoup de ftp acceptent des requΦtes http 
  1645.                // on peut tjs essayer!
  1646.     }
  1647.   } else {
  1648.     int n;
  1649.     p=url;    // sans http://
  1650.     /* Bogus form: 
  1651.        "http:foo.html" means "foo.html" */
  1652.     if ((n=strfield(url,"http:")) !=0 ) {
  1653.       p+=n;
  1654.     }
  1655.   }
  1656.  
  1657.   //## if (adr[0]!=lOCAL_CHAR) {    // adresse normale http
  1658.   if (strcmp(adr,"file://")) {      // PAS file://
  1659.     // p pointe sur le dΘbut de l'adresse, ex: www.truc.fr/sommaire/index.html
  1660.     q=strchr(jump_identification(p),'/');
  1661.     if (q==0) q=p+strlen(p);  // pointe sur \0
  1662.     // pointe sur le chemin, ex: index.html?query=recherche
  1663.     
  1664.     // chemin www... trop long!!
  1665.     if ( ( ((int) q)- ((int) p) )  > HTS_URLMAXSIZE) {
  1666.       //strcpy(retour.msg,"Path too long");
  1667.       return -1;    // erreur
  1668.     }
  1669.     
  1670.     // recopier adresse www..
  1671.     strncat(adr,p, ((int) q) - ((int) p) );
  1672.     // *( adr+( ((int) q) - ((int) p) ) )=0;  // faut arrΩter la fumette!
  1673.     // recopier chemin /pub/..
  1674.     strcat(fil,q);
  1675.     if (strnotempty(fil)==0)    // page par dΘfaut (/)
  1676.       strcat(fil,"/");
  1677.     // SECURITE:
  1678.     // simplifier url pour les ../
  1679.     fil_simplifie(fil);
  1680.   } else {    // localhost file://
  1681.     int i;
  1682.     char* a;
  1683.     strcat(fil,p);    // fichier local ; adr="#"
  1684.     a=strchr(fil,'?');
  1685.     if (a) 
  1686.       *a='\0';      /* couper query (inutile pour file:// lors de la requΩte) */
  1687.     // filtrer les \\ -> / pour les fichiers DOS
  1688.     for(i=0;i<(int) strlen(fil);i++)
  1689.       if (fil[i]=='\\')
  1690.         fil[i]='/';
  1691.   }
  1692.  
  1693.   // nommer au besoin.. (non utilisΘ normalement)
  1694.   if (strnotempty(fil)==0)
  1695.     strcpy(fil,"default-index.html");
  1696.  
  1697.   // case insensitive pour adresse
  1698.   {
  1699.     char *a=jump_identification(adr);
  1700.     while(*a) {
  1701.       if ((*a>='A') && (*a<='Z'))
  1702.         *a+='a'-'A';       
  1703.       a++;
  1704.     }
  1705.   }
  1706.   
  1707.   return 0;
  1708. }
  1709.  
  1710. // simplification des ../
  1711. void fil_simplifie(char* f) {
  1712.   int i=0;
  1713.   int last=0;
  1714.   char* a;
  1715.  
  1716.   // Θliminer ../
  1717.   while (f[i]) {
  1718.     
  1719.     if (f[i]=='/') {
  1720.       if (f[i+1]=='.')
  1721.       if (f[i+2]=='.')      // couper dernier rΘpertoire
  1722.       if (f[i+3]=='/')      // Θviter les /tmp/..coolandlamedir/
  1723.       {    // couper dernier rΘpertoire
  1724.         char tempo[HTS_URLMAXSIZE*2];
  1725.         tempo[0]='\0';
  1726.         //
  1727.         if (!last)                /* can't go upper.. */
  1728.           strcpy(tempo,"/");
  1729.         else
  1730.           strncpy(tempo,f,last+1);
  1731.         tempo[last+1]='\0';
  1732.         strcat(tempo,f+i+4);
  1733.         strcpy(f,tempo);    // remplacer
  1734.         i=-1;             // recommencer
  1735.         last=0;
  1736.       }
  1737.       
  1738.       if (i>=0)
  1739.         last=i;
  1740.       else
  1741.         last=0;
  1742.     }
  1743.     
  1744.     i++;
  1745.   }
  1746.  
  1747.   // Θliminer ./
  1748.   while ( (a=strstr(f,"./")) ) {
  1749.     char tempo[HTS_URLMAXSIZE*2];
  1750.     tempo[0]='\0';
  1751.     strcpy(tempo,a+2);
  1752.     strcpy(a,tempo);
  1753.   }
  1754.   // delete all remaining ../ (potential threat)
  1755.   while ( (a=strstr(f,"../")) ) {
  1756.     char tempo[HTS_URLMAXSIZE*2];
  1757.     tempo[0]='\0';
  1758.     strcpy(tempo,a+3);
  1759.     strcpy(a,tempo);
  1760.   }
  1761.   
  1762. }
  1763.  
  1764.  
  1765. // fermer liaison fichier ou socket
  1766. HTS_INLINE void deletehttp(htsblk* r) {
  1767. #if HTS_DEBUG_CLOSESOCK
  1768.     char info[256];
  1769.     sprintf(info,"deletehttp: (htsblk*) %d\n",r);
  1770.     DEBUG_W2(info);
  1771. #endif
  1772.   if (r->soc!=INVALID_SOCKET) {
  1773.     if (r->is_file) {
  1774.       if (r->fp)
  1775.         fclose(r->fp);
  1776.       r->fp=NULL;
  1777.     } else {
  1778.       if (r->soc!=LOCAL_SOCKET_ID)
  1779.         deletesoc(r->soc);
  1780.     }
  1781.     r->soc=INVALID_SOCKET;
  1782.   }
  1783. }
  1784.  
  1785. // fermer une socket
  1786. HTS_INLINE void deletesoc(T_SOC soc) {
  1787.   if (soc!=INVALID_SOCKET) {
  1788. // J'ai plantΘ.. pas de shutdown
  1789. //#if HTS_WIDE_DEBUG    
  1790. //    DEBUG_W("shutdown\n");
  1791. //#endif
  1792. //    shutdown(soc,2);  // shutdown
  1793. //#if HTS_WIDE_DEBUG    
  1794. //    DEBUG_W("shutdown done\n");
  1795. //#endif
  1796.     // Ne pas oublier de fermer la connexion avant de partir.. (plus propre)
  1797. #if HTS_WIDE_DEBUG    
  1798.     DEBUG_W("close\n");
  1799. #endif
  1800. #if HTS_WIN
  1801.     closesocket(soc);
  1802. #else
  1803.     close(soc);
  1804. #endif
  1805. #if HTS_WIDE_DEBUG    
  1806.     DEBUG_W("close done\n");
  1807. #endif
  1808.   }
  1809. }
  1810.  
  1811. // renvoi le nombre de secondes depuis 1970
  1812. HTS_INLINE double time_local() {
  1813.   return ((double) time(NULL));
  1814. }
  1815.  
  1816. // number of millisec since 1970
  1817. HTS_INLINE double mtime_local() {
  1818. #ifndef HTS_DO_NOT_USE_FTIME
  1819.   struct timeb B;
  1820.   ftime( &B );
  1821.   return (double) ( ((double) B.time * (double) 1000.0)
  1822.         + ((double) B.millitm) );
  1823. #else
  1824.   // not precise..
  1825.   return (double) ( ((double) time_local() * (double) 1000.0)
  1826.         + ((double) 0) );
  1827. #endif
  1828. }
  1829.  
  1830. // convertit un nombre de secondes en temps (chaine)
  1831. void sec2str(char *st,double t) {
  1832.   int j,h,m,s;
  1833.   
  1834.   j=(int) (t/(3600.0*24.0));
  1835.   t-=((double) j)*(3600.0*24.0);
  1836.   h=(int) (t/(3600.0));
  1837.   t-=((double) h)*3600.0;
  1838.   m=(int) (t/60.0);
  1839.   t-=((double) m)*60.0;
  1840.   s=(int) t;
  1841.   
  1842.   if (j>0)
  1843.     sprintf(st,"%d days, %d hours %d minutes %d seconds",j,h,m,s);
  1844.   else if (h>0)
  1845.     sprintf(st,"%d hours %d minutes %d seconds",h,m,s);
  1846.   else if (m>0)
  1847.     sprintf(st,"%d minutes %d seconds",m,s);
  1848.   else
  1849.     sprintf(st,"%d seconds",s);
  1850. }
  1851.  
  1852. // idem, plus court (chaine)
  1853. void qsec2str(char *st,double t) {
  1854.   int j,h,m,s;
  1855.   
  1856.   j=(int) (t/(3600.0*24.0));
  1857.   t-=((double) j)*(3600.0*24.0);
  1858.   h=(int) (t/(3600.0));
  1859.   t-=((double) h)*3600.0;
  1860.   m=(int) (t/60.0);
  1861.   t-=((double) m)*60.0;
  1862.   s=(int) t;
  1863.   
  1864.   if (j>0)
  1865.     sprintf(st,"%dd,%02dh,%02dmin%02ds",j,h,m,s);
  1866.   else if (h>0)
  1867.     sprintf(st,"%dh,%02dmin%02ds",h,m,s);
  1868.   else if (m>0)
  1869.     sprintf(st,"%dmin%02ds",m,s);
  1870.   else
  1871.     sprintf(st,"%ds",s);
  1872. }
  1873.  
  1874.  
  1875. // heure actuelle, GMT, format rfc (taille buffer 256o)
  1876. void time_gmt_rfc822(char* s) {
  1877.   time_t tt;
  1878.   struct tm* A;
  1879.   tt=time(NULL);
  1880.   A=gmtime(&tt);
  1881.   if (A==NULL)
  1882.     A=localtime(&tt);
  1883.   time_rfc822(s,A);
  1884. }
  1885.  
  1886. // heure actuelle, format rfc (taille buffer 256o)
  1887. void time_local_rfc822(char* s) {
  1888.   time_t tt;
  1889.   struct tm* A;
  1890.   tt=time(NULL);
  1891.   A=localtime(&tt);
  1892.   time_rfc822_local(s,A);
  1893. }
  1894.  
  1895. /* convertir une chaine en temps */
  1896. struct tm* convert_time_rfc822(char* s) {
  1897.   static struct tm result;
  1898.   /* */
  1899.   char months[]="jan feb mar apr may jun jul aug sep oct nov dec";
  1900.   char str[256];
  1901.   char* a;
  1902.   /* */
  1903.   int result_mm=-1;
  1904.   int result_dd=-1;
  1905.   int result_n1=-1;
  1906.   int result_n2=-1;
  1907.   int result_n3=-1;
  1908.   int result_n4=-1;
  1909.   /* */
  1910.   if ((int) strlen(s) > 200)
  1911.     return NULL;
  1912.   strcpy(str,s);
  1913.   hts_lowcase(str);
  1914.   /* Θliminer :,- */
  1915.   while( (a=strchr(str,'-')) ) *a=' ';
  1916.   while( (a=strchr(str,':')) ) *a=' ';
  1917.   while( (a=strchr(str,',')) ) *a=' ';
  1918.   /* tokeniser */
  1919.   a=str;
  1920.   while(*a) {
  1921.     char *first,*last;
  1922.     char tok[256];
  1923.     /* dΘcouper mot */
  1924.     while(*a==' ') a++;   /* sauter espaces */
  1925.     first=a;
  1926.     while((*a) && (*a!=' ')) a++;
  1927.     last=a;
  1928.     tok[0]='\0';
  1929.     if (first!=last) {
  1930.       char* pos;
  1931.       strncat(tok,first,(int) last-(int) first);
  1932.       /* analyser */
  1933.       if ( (pos=strstr(months,tok)) ) {               /* month always in letters */
  1934.         result_mm=((int) pos-(int) months)/4;
  1935.       } else {
  1936.         int number;
  1937.         if (sscanf(tok,"%d",&number) == 1) {      /* number token */
  1938.           if (result_dd<0)                        /* day always first number */
  1939.             result_dd=number;
  1940.           else if (result_n1<0)
  1941.             result_n1=number;
  1942.           else if (result_n2<0)
  1943.             result_n2=number;
  1944.           else if (result_n3<0)
  1945.             result_n3=number;
  1946.           else if (result_n4<0)
  1947.             result_n4=number;
  1948.         }   /* sinon, bruit de fond(+1GMT for exampel) */
  1949.       }
  1950.     }
  1951.   }
  1952.   if ((result_n1>=0) && (result_mm>=0) && (result_dd>=0) && (result_n2>=0) && (result_n3>=0) && (result_n4>=0)) {
  1953.     if (result_n4>=1000) {               /* Sun Nov  6 08:49:37 1994 */
  1954.       result.tm_year=result_n4-1900;
  1955.       result.tm_hour=result_n1;
  1956.       result.tm_min=result_n2;
  1957.       result.tm_sec=max(result_n3,0);
  1958.     } else {                            /* Sun, 06 Nov 1994 08:49:37 GMT or Sunday, 06-Nov-94 08:49:37 GMT */
  1959.       result.tm_hour=result_n2;
  1960.       result.tm_min=result_n3;
  1961.       result.tm_sec=max(result_n4,0);
  1962.       if (result_n1<=50)                /* 00 means 2000 */
  1963.         result.tm_year=result_n1+100;
  1964.       else if (result_n1<1000)          /* 99 means 1999 */
  1965.         result.tm_year=result_n1;
  1966.       else                              /* 2000 */
  1967.         result.tm_year=result_n1-1900;
  1968.     }
  1969.     result.tm_isdst=0;        /* assume GMT */
  1970.     result.tm_yday=-1;        /* don't know */
  1971.     result.tm_wday=-1;        /* don't know */
  1972.     result.tm_mon=result_mm;
  1973.     result.tm_mday=result_dd;
  1974.     return &result;
  1975.   }
  1976.   return NULL;
  1977. }
  1978.  
  1979. /* sets file time. -1 if error */
  1980. int set_filetime(char* file,struct tm* tm_time) {
  1981.   struct utimbuf tim;
  1982. #ifndef HTS_DO_NOT_USE_FTIME
  1983.   struct timeb B;
  1984.   B.timezone=0;
  1985.   ftime( &B );
  1986.   tim.actime=tim.modtime=mktime(tm_time) - B.timezone*60; 
  1987. #else
  1988.   // bogus time (GMT/local)..
  1989.   tim.actime=tim.modtime=mktime(tm_time); 
  1990. #endif
  1991.   return utime(file,&tim);
  1992. }
  1993.  
  1994. /* sets file time from RFC822 date+time, -1 if error*/
  1995. int set_filetime_rfc822(char* file,char* date) {
  1996.   struct tm* tm_s=convert_time_rfc822(date);
  1997.   if (tm_s) {
  1998.     return set_filetime(file,tm_s);
  1999.   } else return -1;
  2000. }
  2001.  
  2002.  
  2003. // heure au format rfc (taille buffer 256o)
  2004. HTS_INLINE void time_rfc822(char* s,struct tm * A) {
  2005.   strftime(s,256,"%a, %d %b %Y %H:%M:%S GMT",A);
  2006. }
  2007.  
  2008. // heure locale au format rfc (taille buffer 256o)
  2009. HTS_INLINE void time_rfc822_local(char* s,struct tm * A) {
  2010.   strftime(s,256,"%a, %d %b %Y %H:%M:%S",A);
  2011. }
  2012.  
  2013. // conversion en b,Kb,Mb
  2014. char* int2bytes(LLint n) {
  2015.   static char buff[256];
  2016.   char** a=int2bytes2(n);
  2017.   strcpy(buff,a[0]);
  2018.   strcat(buff,a[1]);
  2019.   return buff;
  2020. }
  2021.  
  2022. // conversion en b/s,Kb/s,Mb/s
  2023. char* int2bytessec(long int n) {
  2024.   static char buff[256];
  2025.   char** a=int2bytes2(n);
  2026.   strcpy(buff,a[0]);
  2027.   strcat(buff,a[1]);
  2028.   return concat(buff,"/s");
  2029. }
  2030.  
  2031. // conversion en b,Kb,Mb, nombre et type sΘparΘs
  2032. // limite: 2.10^9.10^6B
  2033. char** int2bytes2(LLint n) {
  2034.   static char buff1[256];
  2035.   static char buff2[32];
  2036.   static char* buffadr[2];
  2037.   if (n<1024) {
  2038.     sprintf(buff1,"%d",(int)n);
  2039.     strcpy(buff2,"B");
  2040.   } else if (n<(1024*1024)) {
  2041.     sprintf(buff1,"%d,%02d",(int)(n/1024),(int)((n%1024)*100)/1024);
  2042.     strcpy(buff2,"KB");
  2043.   } else {
  2044.     sprintf(buff1,"%d,%02d",(int)(n/(1024*1024)),(int)(((n%(1024*1024))*100)/(1024*1024)));
  2045.     strcpy(buff2,"MB");
  2046.   }
  2047.   buffadr[0]=buff1;
  2048.   buffadr[1]=buff2;
  2049.   return buffadr;
  2050. }
  2051.  
  2052.  
  2053. // envoi de texte (en tΩtes gΘnΘralement) sur la socket soc
  2054. HTS_INLINE int sendc(T_SOC soc,char* s) {
  2055. #if HDEBUG
  2056.   write(0,s,strlen(s));
  2057. #endif
  2058. //#if HTS_WIN
  2059.   return send(soc,s,strlen(s),0);
  2060. //#else
  2061. //  return write(soc,s,strlen(s));
  2062. //#endif
  2063. }
  2064.  
  2065.  
  2066. // Remplace read
  2067. void finput(int fd,char* s,int max) {
  2068.   static char c;
  2069.   register int j=0;
  2070.   do {
  2071.     //c=fgetc(fp);
  2072.     if (read(fd,&c,1)<=0) {
  2073.       c=0;
  2074.     }
  2075.     if (c!=0) {
  2076.       switch(c) {
  2077.       case 10: c=0; break;
  2078.       case 13: break;  // sauter ces caractΦres
  2079.       default: s[j++]=c; break;
  2080.       }
  2081.     }
  2082.   }  while((c!=0) && (j<max-1));
  2083.   s[j++]='\0';
  2084.  
  2085. // lire ligne dans buffer, renvoi incrΘment α opΘrer sur l'adresse ensuite
  2086. int binput(char* buff,char* s,int max) {
  2087.   static char c;
  2088.   register int j=0;
  2089.   register int i=0;
  2090.   if ((*buff)=='\0') {  // fin du buffer
  2091.     s[0]='\0';
  2092.     return 0;  // eof  
  2093.   }
  2094.   do {
  2095.     //c=fgetc(fp);
  2096.     c=*(buff++); i++;
  2097.     if (c!=0) {
  2098.       switch(c) {
  2099.       case 10: c=0; break;
  2100.       case 13: break;  // sauter ces caractΦres
  2101.       default: s[j++]=c; break;
  2102.       }
  2103.     }
  2104.   }  while((c!=0) && (j<max-1));
  2105.   s[j++]='\0';
  2106.   return i;
  2107.  
  2108. // Remplace fscanf(fp,"%s",s)
  2109. void linput(FILE* fp,char* s,int max) {
  2110.   register int c;
  2111.   register int j=0;
  2112.   do {
  2113.     c=fgetc(fp);
  2114.     if (c!=EOF) {
  2115.       switch(c) {
  2116.         case 13: break;  // sauter CR
  2117.         case 10: c=-1; break;
  2118.         case 9: case 12: break;  // sauter ces caractΦres
  2119.         default: s[j++]=(char) c; break;
  2120.       }
  2121.     }
  2122.   }  while((c!=-1) && (c!=EOF) && (j<(max-1)));
  2123.   s[j++]='\0';
  2124. }
  2125. void linput_trim(FILE* fp,char* s,int max) {
  2126.   char* ls=(char*) malloc(max+2);
  2127.   if (ls) {
  2128.     char* a;
  2129.     // lire ligne
  2130.     linput(fp,ls,max);
  2131.     // sauter espaces et tabs en fin
  2132.     while((ls[strlen(ls)-1]==' ') || (ls[strlen(ls)-1]=='\t')) ls[strlen(ls)-1]='\0';
  2133.     // sauter espaces en dΘbut
  2134.     a=ls; while((*a==' ') || (*a=='\t')) a++;
  2135.     strcpy(s,a);
  2136.     //
  2137.     free(ls);
  2138.   }
  2139. }
  2140. void linput_cpp(FILE* fp,char* s,int max) {
  2141.   s[0]='\0';
  2142.   do {
  2143.     if (s[strlen(s)-1]=='\\') s[strlen(s)-1]='\0';      // couper \ final
  2144.     // lire ligne
  2145.     linput_trim(fp,s+strlen(s),max-strlen(s));
  2146.   } while((s[strlen(s)-1]=='\\') && ((int)strlen(s)<max));
  2147. }
  2148.  
  2149. // idem avec les car spΘciaux
  2150. void rawlinput(FILE* fp,char* s,int max) {
  2151.   register int c;
  2152.   register int j=0;
  2153.   do {
  2154.     c=fgetc(fp);
  2155.     if (c!=EOF) {
  2156.       switch(c) {
  2157.         case 13: break;  // sauter CR
  2158.         case 10: c=-1; break;
  2159.         default: s[j++]=(char) c; break;
  2160.       }
  2161.     }
  2162.   }  while((c!=-1) && (c!=EOF) && (j<(max-1)));
  2163.   s[j++]='\0';
  2164. }
  2165.  
  2166.  
  2167. // compare le dΘbut de f avec s et retourne la position de la fin
  2168. // 'A=a' (case insensitive)
  2169. int strfield(const char* f,const char* s) {
  2170.   register int r=0;
  2171.   while (streql(*f,*s) && ((*f)!=0) && ((*s)!=0)) { f++; s++; r++; }
  2172.   if (*s==0)
  2173.     return r;
  2174.   else
  2175.     return 0;
  2176. }
  2177.  
  2178. //cherche chaine, case insensitive
  2179. char* strstrcase(char *s,char *o) {
  2180.   while((*s) && (strfield(s,o)==0)) s++;
  2181.   if (*s=='\0') return NULL;
  2182.   return s;  
  2183. }
  2184.  
  2185.  
  2186. // le fichier est-il un fichier html?
  2187. //  0 : non
  2188. //  1 : oui
  2189. // -1 : on sait pas
  2190. // -2 : on sait pas, pas d'extension
  2191. int ishtml(char* fil) {
  2192.   char *a;
  2193.  
  2194.   // patch pour les truc.html?Choix=toto
  2195.   if ( (a=strchr(fil,'?')) )  // paramΦtres?
  2196.     a--;  // pointer juste avant le ?
  2197.   else
  2198.     a=fil+strlen(fil)-1;  // pointer sur le dernier caractΦre
  2199.  
  2200.   if (*a=='/') return -1;    // rΘpertoire, on sait pas!!
  2201.   //if (*a=='/') return 1;    // ok rΘpertoire, html
  2202.  
  2203.   while ( (*a!='.') && (*a!='/')  && ((int) a>(int) fil)) a--;
  2204.   if (*a=='.') {  // a une extension
  2205.     a++;  // pointer sur extension
  2206.     return ishtml_ext(a);     // retour
  2207.   } else return -2;   // indΘterminΘ, par exemple /truc
  2208. }
  2209.  
  2210. // idem, mais pour uniquement l'extension
  2211. int ishtml_ext(char* a) {
  2212.   int html=0;  
  2213.   //
  2214.   if (strfield2(a,"html"))  html = 1;
  2215.   else if (strfield2(a,"htm"))   html = 1;
  2216.   else if (strfield2(a,"shtml")) html = 1;
  2217.   else if (strfield2(a,"htmlx")) html = 1;
  2218.   else if (strfield2(a,"shtm"))  html = 1;
  2219.   else if (strfield2(a,"htmx"))  html = 1;
  2220.   //
  2221.   else if (strfield2(a,"asp"))   html = -1;
  2222.   else if (strfield2(a,"cgi"))   html = -1;    // indΘterminΘ
  2223.   //
  2224.   // insuccΦs..
  2225.   else {
  2226.     if (is_knowntype(a))
  2227.       html = 0;     // connu, non html (html ont ΘtΘ testΘs avant)
  2228.     else
  2229.       html = -1;    // inconnu..
  2230.   }
  2231.   return html;  
  2232. }
  2233.  
  2234. // error (404,500..)
  2235. HTS_INLINE int ishttperror(int err) {
  2236.   switch (err/100) {
  2237.     case 4: case 5: return 1;
  2238.       break;
  2239.   }
  2240.   return 0;
  2241. }
  2242.  
  2243.  
  2244. // retourne le pointeur ou le pointeur + offset si il existe dans la chaine un @ signifiant une identification
  2245. char* jump_identification(char* source) {
  2246.   char *a,*b;
  2247.   // rechercher dernier @ (car parfois email transmise dans adresse!)
  2248.   // mais sauter ftp:// Θventuel
  2249.   a = jump_protocol(source);
  2250.   while( (b = strchr(a,'@')) ) {
  2251.     char* c;
  2252.     if ( (c=strchr(a,'/')) )        /* si un / est trouvΘ */
  2253.     if ((int) c < (int) b)      /* avant le @ */
  2254.       return a;                 /* alors exit (http://www.foo.bar/1.html@A20) */
  2255.     a=b+1;
  2256.   }
  2257.   return a;
  2258. }
  2259.  
  2260. // retourner adr sans ftp://
  2261. HTS_INLINE char* jump_protocol(char* source) {
  2262.   if (strncmp(source,"ftp://",6)==0)
  2263.     return source+6;
  2264.   else if (strncmp(source,"http://",7)==0)
  2265.     return source+7;
  2266.   /* bogus form: http:relative.html */
  2267.   else if (strncmp(source,"http:",5)==0)
  2268.     return source+5;
  2269.   return source;
  2270. }
  2271.  
  2272. // codage base 64 a vers b
  2273. void code64(char* a,char* b) {
  2274.   int i1=0,i2=0,i3=0,i4=0;
  2275.   unsigned long store;
  2276.   int n;
  2277.   const char _hts_base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2278.   b[0]='\0';
  2279.   while(*a) {  
  2280.     // 24 bits
  2281.     n=1; store=0; store |= ((*a++) & 0xff);
  2282.     if (*a) { n=2; store <<= 8; store |= ((*a++) & 0xff); }
  2283.     if (*a) { n=3; store <<= 8; store |= ((*a++) & 0xff); }
  2284.     if (n==3) {
  2285.       i4=store & 63;
  2286.       i3=(store>>6) & 63;
  2287.       i2=(store>>12) & 63;
  2288.       i1=(store>>18) & 63;
  2289.     } else if (n==2) {
  2290.       store<<=2;    
  2291.       i3=store & 63;
  2292.       i2=(store>>6) & 63;
  2293.       i1=(store>>12) & 63;
  2294.     } else {
  2295.       store<<=4;
  2296.       i2=store & 63;
  2297.       i1=(store>>6) & 63;
  2298.     }
  2299.     
  2300.     *b++ = _hts_base64[i1];
  2301.     *b++ = _hts_base64[i2];
  2302.     if (n>=2)
  2303.       *b++ = _hts_base64[i3];
  2304.     else
  2305.       *b++ = '=';
  2306.     if (n>=3)
  2307.       *b++ = _hts_base64[i4];
  2308.     else
  2309.       *b++ = '=';
  2310.   }
  2311.   *b++='\0';
  2312. }
  2313.  
  2314. // remplacer " par " etc..
  2315. // buffer MAX 1Ko
  2316. void unescape_amp(char* s) {
  2317.   while(*s) {
  2318.     if (*s=='&') {
  2319.       char* end=strchr(s,';');
  2320.       if ( ((int) end - (int) s) <= 8) {
  2321.         char c=0;
  2322.         if (strfield(s,"&"))
  2323.           c='&';
  2324.         else if (strfield(s,"°"))
  2325.           c='░';
  2326.         else if (strfield(s,">"))
  2327.           c='>';
  2328.         else if (strfield(s,"«"))
  2329.           c='\"';
  2330.         else if (strfield(s,"<"))
  2331.           c='<';
  2332.         else if (strfield(s," "))
  2333.           c=' ';
  2334.         else if (strfield(s,"""))
  2335.           c='\"';
  2336.         else if (strfield(s,"»"))
  2337.           c='\"';
  2338.         else if (strfield(s,"­"))
  2339.           c='-';
  2340.         else if (strfield(s,"˜"))
  2341.           c='~';
  2342.         else if (strfield(s,"&"))
  2343.           c='&';
  2344.         // remplacer?
  2345.         if (c) {
  2346.           char buff[HTS_URLMAXSIZE*2];
  2347.           buff[0]=c;
  2348.           strcpy(buff+1,end+1);
  2349.           strcpy(s,buff);
  2350.         }
  2351.       }
  2352.     }
  2353.     s++;
  2354.   }
  2355. }
  2356.  
  2357. // remplacer %20 par ' ', | par : etc..
  2358. // buffer MAX 1Ko
  2359. char* unescape_http(char* s) {
  2360.   static char tempo[HTS_URLMAXSIZE*2];
  2361.   int i,j=0;
  2362.   for (i=0;i<(int) strlen(s);i++) {
  2363.     if (s[i]=='%') {
  2364.       i++;
  2365.       tempo[j++]=(char) ehex(s+i);
  2366.       i++;    // sauter 2 caractΦres finalement
  2367.     } else if (s[i]=='|') {                     // exemple: file:///C|Program%20Files...
  2368.       tempo[j++]=':';
  2369.     } else
  2370.       tempo[j++]=s[i];
  2371.   }
  2372.   tempo[j++]='\0';
  2373.   return tempo;
  2374. }
  2375.  
  2376. // remplacer " par %xx etc..
  2377. // buffer MAX 1Ko
  2378. void escape_spc_url(char* s) {
  2379.   x_escape_http(s,2);
  2380. }
  2381. // smith / john -> smith%20%2f%20john
  2382. void escape_in_url(char* s) {
  2383.   x_escape_http(s,1);
  2384. }
  2385. void escape_check_url(char* s) {
  2386.   x_escape_http(s,0);
  2387. }
  2388. void x_escape_http(char* s,int mode) {
  2389.   while(*s) {
  2390.     int test=0;
  2391.     if (mode == 0)
  2392.       test=(strchr("\" ",*s)!=0);
  2393.     else if (mode==1) {
  2394.       // Safe (RFC2396)
  2395.       test=(strchr(";/?:@&=+$,",*s)!=0);
  2396.       // Safe for us..
  2397.       if (!test)
  2398.         test=(strchr(" %*<>#'\"\\",*s)!=0);
  2399.       // Escape >127 (much safer)
  2400.       if (!test)
  2401.         test=((((unsigned char)*s) > 127)?1:0);
  2402.     }
  2403.     else if (mode==2)
  2404.       test=(strchr(" ",*s)!=0);           // n'escaper que espace
  2405.  
  2406.     if (test) {
  2407.       char buffer[HTS_URLMAXSIZE*2];
  2408.       int n;
  2409.       n=(int)(unsigned char) *s;
  2410.       strcpy(buffer,s+1);
  2411.       sprintf(s,"%%%02x",n);
  2412.       strcat(s,buffer);
  2413.     }
  2414.     s++;
  2415.   }
  2416. }
  2417.  
  2418.  
  2419. HTS_INLINE int ehexh(char c) {
  2420.   if ((c>='0') && (c<='9')) return c-'0';
  2421.   if ((c>='a') && (c<='f')) c-=('a'-'A');
  2422.   if ((c>='A') && (c<='F')) return (c-'A'+10);
  2423.   return 0;
  2424. }
  2425.  
  2426. HTS_INLINE int ehex(char* s) {
  2427.   return 16*ehexh(*s)+ehexh(*(s+1));
  2428.  
  2429. }
  2430.  
  2431. // concat, concatΦne deux chaines et renvoi le rΘsultat
  2432. // permet d'allΘger grandement le code
  2433. // il faut savoir qu'on ne peut mettre plus de 8 concat() dans une expression
  2434. char* concat(const char* a,const char* b) {
  2435.   static char buff[8][HTS_URLMAXSIZE*2];
  2436.   static int rol;
  2437.   rol=((rol+1)%8);    // roving pointer
  2438.   strcpy(buff[rol],a);
  2439.   if (b) strcat(buff[rol],b);
  2440.   return buff[rol];
  2441. }
  2442. // conversion fichier / -> antislash
  2443. #if HTS_DOSNAME
  2444. char* __fconv(char* a) {
  2445.   int i;
  2446.   for(i=0;i<(int) strlen(a);i++)
  2447.     if (a[i]=='/')  // convertir
  2448.       a[i]='\\';
  2449.   return a;
  2450. }
  2451. char* fconcat(char* a,char* b) {
  2452.   return __fconv(concat(a,b));
  2453. }
  2454. char* fconv(char* a) {
  2455.   return __fconv(concat(a,""));
  2456. }
  2457. #endif
  2458.  
  2459. /* / et \\ en / */
  2460. char* __fslash(char* a) {
  2461.   int i;
  2462.   for(i=0;i<(int) strlen(a);i++)
  2463.     if (a[i]=='\\')  // convertir
  2464.       a[i]='/';
  2465.   return a;
  2466. }
  2467. char* fslash(char* a) {
  2468.   return __fslash(concat(a,""));
  2469. }
  2470.  
  2471. // conversion minuscules, avec buffer
  2472. char* convtolower(char* a) {
  2473.   static char buff[8][HTS_URLMAXSIZE*2];
  2474.   static int rol;
  2475.   rol=((rol+1)%8);    // roving pointer
  2476.   strcpy(buff[rol],a);
  2477.   hts_lowcase(buff[rol]);  // lower case
  2478.   return buff[rol];
  2479. }
  2480.  
  2481. // conversion en minuscules
  2482. void hts_lowcase(char* s) {
  2483.   register int i;
  2484.   for(i=0;i<(int) strlen(s);i++)
  2485.     if ((s[i]>='A') && (s[i]<='Z'))
  2486.       s[i]+=('a'-'A');
  2487. }
  2488.  
  2489. // remplacer un caractΦre d'une chaεne dans une autre
  2490. HTS_INLINE void hts_replace(char *s,char from,char to) { 
  2491.   register char* a;
  2492.   while ((a=strchr(s,from))!=NULL) {
  2493.     *a=to;
  2494.   }
  2495. }
  2496.  
  2497.  
  2498. // caractΦre espace, guillemets, CR, LF etc..
  2499. /* SECTION OPTIMISEE:
  2500.   #define  is_space(c) (strchr(" \"\x0d\x0a\x09'",c)!=NULL)
  2501.   #define  is_realspace(c) (strchr(" \x0d\x0a\x09",c)!=NULL)
  2502. */
  2503. /*
  2504. HTS_INLINE int is_space(char c) {
  2505.   if (c==' ')  return 1;  // spc
  2506.   if (c=='"')  return 1;  // quote
  2507.   if (c==10)   return 1;  // lf
  2508.   if (c==13)   return 1;  // cr
  2509.   if (c=='\'') return 1;  // quote
  2510.   //if (c=='`')  return 1;  // backquote      << non
  2511.   if (c==9)    return 1;  // tab
  2512.   return 0;
  2513. }
  2514. */
  2515.  
  2516. // caractΦre espace, CR, LF, TAB
  2517. /*
  2518. HTS_INLINE int is_realspace(char c) {
  2519.   if (c==' ')  return 1;  // spc
  2520.   if (c==10)   return 1;  // lf
  2521.   if (c==13)   return 1;  // cr
  2522.   if (c==9)    return 1;  // tab
  2523.   return 0;
  2524. }
  2525. */
  2526.  
  2527.  
  2528.  
  2529.  
  2530.  
  2531. // deviner type d'un fichier local..
  2532. // ex: fil="toto.gif" -> s="image/gif"
  2533. void guess_httptype(char *s,char *fil) {
  2534.   get_httptype(s,fil,1);
  2535. }
  2536. // idem
  2537. // flag: 1 si toujours renvoyer un type
  2538. void get_httptype(char *s,char *fil,int flag) {
  2539.   if (ishtml(fil)==1)
  2540.     strcpy(s,"text/html");
  2541.   else {
  2542.     char *a=fil+strlen(fil)-1;    
  2543.     while ( (*a!='.') && (*a!='/')  && (a>fil)) a--;
  2544.     if (*a=='.') {
  2545.       int ok=0;
  2546.       int j=0;
  2547.       a++;
  2548.       while( (!ok) && (strnotempty(hts_mime[j][1])) ) {
  2549.         if (strfield2(hts_mime[j][1],a)) {
  2550.           if (hts_mime[j][0][0]!='*') {    // Une correspondance existe
  2551.             strcpy(s,hts_mime[j][0]);
  2552.             ok=1;
  2553.           }
  2554.         }
  2555.         j++;
  2556.       }
  2557.       
  2558.       if (!ok) if (flag) sprintf(s,"application/%s",a);
  2559.     } else {
  2560.       if (flag) strcpy(s,"application/octet-stream");
  2561.     }
  2562.   }
  2563. }
  2564. // renvoyer extesion d'un type mime..
  2565. // ex: "image/gif" -> gif
  2566. void give_mimext(char *s,char *st) {   
  2567.   int ok=0;
  2568.   int j=0;
  2569.   strcpy(s,"");
  2570.   while( (!ok) && (strnotempty(hts_mime[j][1])) ) {
  2571.     if (strfield2(hts_mime[j][0],st)) {
  2572.       if (hts_mime[j][1][0]!='*') {    // Une correspondance existe
  2573.         strcpy(s,hts_mime[j][1]);
  2574.         ok=1;
  2575.       }
  2576.     }
  2577.     j++;
  2578.   }    
  2579. }
  2580. // extension connue?..
  2581. int is_knowntype(char *fil) {
  2582.   int j=0;
  2583.   while(strnotempty(hts_mime[j][1])) {
  2584.     if (strfield2(hts_mime[j][1],fil)) {
  2585.       return 1;
  2586.     }
  2587.     j++;
  2588.   }
  2589.   return 0;
  2590. }
  2591. // extension : html,gif..
  2592. char* get_ext(char *fil) {
  2593.   char *a=fil+strlen(fil)-1;    
  2594.   while ( (*a!='.') && (*a!='/')  && (a>fil)) a--;
  2595.   if (*a=='.')
  2596.     return a+1;
  2597.   else
  2598.     return NULL;
  2599. }
  2600.  
  2601. // types critiques qui ne doivent pas Ωtre changΘs car renvoyΘs par des serveurs qui ne
  2602. // connaissent pas le type
  2603. int may_unknown(char* st) {
  2604.   int j=0;
  2605.   // types mΘdia
  2606.   if (may_be_hypertext_mime(st))
  2607.     return 1;
  2608.   while(strnotempty(hts_mime_keep[j])) {
  2609.     if (strfield2(hts_mime_keep[j],st)) {      // trouvΘ
  2610.       return 1;
  2611.     }
  2612.     j++;
  2613.   }    
  2614.   return 0;
  2615. }
  2616.  
  2617.  
  2618. // -- Utils fichiers
  2619. /* Le fichier existe-t-il? (ou est-il HTS_ACCESSible?) */
  2620. int fexist(char* s) {
  2621.   FILE* fp;
  2622.   if (strnotempty(s)==0)     // nom vide: non trouvΘ
  2623.     return 0;
  2624.   fp=fopen(fconv(s),"rb");
  2625.   if (fp!=NULL) fclose(fp);
  2626.   return (fp!=NULL);
  2627.  
  2628. /* Taille d'un fichier, -1 si n'existe pas */
  2629. /* fp->_cnt ne fonctionne pas sur toute les plate-formes :-(( */
  2630. /* Note: NOT YET READY FOR 64-bit */
  2631. //LLint fsize(char* s) {
  2632. int fsize(char* s) {
  2633.   /*
  2634. #if HTS_WIN
  2635.   HANDLE hFile;
  2636.   DWORD dwSizeHigh = 0;
  2637.   DWORD dwSizeLow  = 0;
  2638.   hFile = CreateFile(s,0,0,NULL,OPEN_EXISTING,0,NULL);
  2639.   if (hFile) {
  2640.     dwSizeLow = GetFileSize (hFile, & dwSizeHigh) ;
  2641.     CloseHandle(hFile);
  2642.     if (dwSizeLow != 0xFFFFFFFF)
  2643.       return (dwSizeLow & (dwSizeHigh<<32));
  2644.     else
  2645.       return -1;
  2646.   } else
  2647.     return -1;
  2648. #else
  2649.     */
  2650.   FILE* fp;
  2651.   if (strnotempty(s)==0)     // nom vide: erreur
  2652.     return -1;
  2653.   fp=fopen(fconv(s),"rb");
  2654.   if (fp!=NULL) {
  2655.     int i;
  2656.     fseek(fp,0,SEEK_END);
  2657.     i=ftell(fp);
  2658.     fclose(fp);
  2659.     return i;
  2660.   } else return -1;
  2661.   /*
  2662. #endif
  2663.   */
  2664. }
  2665.  
  2666. int fpsize(FILE* fp) {
  2667.   int oldpos,size;
  2668.   if (!fp)
  2669.     return -1;
  2670.   oldpos=ftell(fp);
  2671.   fseek(fp,0,SEEK_END);
  2672.   size=ftell(fp);
  2673.   fseek(fp,oldpos,SEEK_SET);
  2674.   return size;
  2675. }
  2676.  
  2677.  
  2678. hts_stat_struct HTS_STAT;
  2679. //LLint HTS_TOTAL_RECV = 0;  // flux entrant reτu
  2680. //int HTS_TOTAL_RECV_STATE = 0;  // status: 0 tout va bien 1: ralentir un peu 2: ralentir 3: beaucoup
  2681. void HTS_TOTAL_RECV_CHECK(int var) {
  2682.   if (HTS_STAT.HTS_TOTAL_RECV_STATE) { 
  2683.     if (HTS_STAT.HTS_TOTAL_RECV_STATE==3) { 
  2684.       var = min(var,32); 
  2685.       Sleep(250); 
  2686.     } else if (HTS_STAT.HTS_TOTAL_RECV_STATE==2) { 
  2687.       var = min(var,256); 
  2688.       Sleep(100); 
  2689.     } else { 
  2690.       var/=2; 
  2691.       if (var<=0) var=1; 
  2692.       Sleep(50); 
  2693.     } 
  2694.   }
  2695. }
  2696.  
  2697. // Lecture dans buff de size octets au maximum en utilisant la socket r (structure htsblk)
  2698. HTS_INLINE int hts_read(htsblk* r,char* buff,int size) {
  2699.   register int retour;
  2700.   //  return read(soc,buff,size);
  2701.   if (r->is_file) {
  2702. #if HTS_WIDE_DEBUG    
  2703.     DEBUG_W("read\n");
  2704. #endif
  2705.     if (r->fp)
  2706.       retour=fread(buff,1,size,r->fp);
  2707.     else
  2708.       retour=-1;
  2709.   } else {
  2710. #if HTS_WIDE_DEBUG    
  2711.     DEBUG_W("recv\n");
  2712.     if (r->soc==INVALID_SOCKET)
  2713.       printf("!!WIDE_DEBUG ERROR, soc==INVALID hts_read\n");
  2714. #endif
  2715.     HTS_TOTAL_RECV_CHECK(size);         // Diminuer au besoin si trop de donnΘes reτues
  2716.     retour=recv(r->soc,buff,size,0);
  2717.     if (retour>0)    // compter flux entrant
  2718.       HTS_STAT.HTS_TOTAL_RECV+=retour;
  2719.   }
  2720. #if HTS_WIDE_DEBUG    
  2721.   DEBUG_W("recv/read done\n");
  2722. #endif
  2723.   return retour;
  2724. }
  2725.  
  2726.  
  2727. // -- Gestion cache DNS --
  2728. // 'RX98
  2729. #if HTS_DNSCACHE
  2730.  
  2731. // 'capsule' contenant uniquement le cache
  2732. t_dnscache* _hts_cache() {
  2733.   static t_dnscache cache;
  2734.   return &cache;
  2735. }
  2736.  
  2737. // lock le cache dns pour tout opΘration d'ajout
  2738. // plus prudent quand plusieurs threads peuvent Θcrire dedans..
  2739. // -1: status? 0: libΘrer 1:locker
  2740.  
  2741. /* 
  2742.   Simple lock function for cache
  2743.  
  2744.   Return value: always 0
  2745.   Parameter:
  2746.   1 wait for lock (mutex) available and lock it
  2747.   0 unlock the mutex
  2748.   [-1 check if locked (always return 0 with mutex)]
  2749.   -999 initialize
  2750. */
  2751. #if USE_BEGINTHREAD
  2752. int _hts_lockdns(int i) {
  2753.   static PTHREAD_LOCK_TYPE hMutex; 
  2754.   return htsSetLock(&hMutex,i);
  2755. }
  2756. #else
  2757. int _hts_lockdns(int i) {
  2758.   static int l=0;
  2759.   if (i>=0)
  2760.     l=i;
  2761.   return l;
  2762. }
  2763. #endif
  2764.  
  2765. // routine pour le cache - retour optionnel α donner α chaque fois
  2766. // NULL: nom non encore testΘ dans le cache
  2767. // si h_length==0 alors le nom n'existe pas dans le dns
  2768. t_hostent* _hts_ghbn(t_dnscache* cache,char* iadr,t_hostent* retour) {
  2769.   // attendre que le cache dns soit prΩt
  2770.   while(_hts_lockdns(-1));  // attendre libΘration
  2771.   _hts_lockdns(1);          // locker
  2772.  
  2773.   while(1) {
  2774.     if (strcmp(cache->iadr,iadr)==0) {  // ok trouvΘ
  2775.       if (cache->host_length>0) {  // entrΘe valide
  2776.         if (retour->h_addr)
  2777.           bcopy(cache->host_addr,(char *)retour->h_addr,cache->host_length);
  2778.         retour->h_length=cache->host_length;
  2779.       } else if (cache->host_length==0) {  // en cours
  2780.         _hts_lockdns(0);          // dΘlocker
  2781.         return NULL;
  2782.       } else {                    // erreur dans le dns, dΘja vΘrifiΘ
  2783.         if (retour->h_addr)
  2784.           retour->h_addr[0]='\0';
  2785.         retour->h_length=0;  // erreur, n'existe pas
  2786.       }
  2787.       _hts_lockdns(0);          // dΘlocker
  2788.       return retour;
  2789.     } else {    // on a pas encore trouvΘ
  2790.       if (cache->n!=NULL) { // chercher encore
  2791.         cache=cache->n;   // suivant!
  2792.       } else {
  2793.         _hts_lockdns(0);          // dΘlocker
  2794.         return NULL;    // non prΘsent        
  2795.       }
  2796.     }    
  2797.   }
  2798. }
  2799.  
  2800. // tester si iadr a dΘja ΘtΘ testΘ (ou en cours de test)
  2801. // 0 non encore
  2802. // 1 ok
  2803. // 2 non prΘsent
  2804. int hts_dnstest(char* _iadr) {
  2805.   static char iadr[HTS_URLMAXSIZE*2];
  2806.   t_dnscache* cache=_hts_cache();  // adresse du cache 
  2807.  
  2808.   // sauter user:pass@ Θventuel
  2809.   strcpy(iadr,jump_identification(_iadr));
  2810.   // couper Θventuel :
  2811.   {
  2812.     char *a;
  2813.     if ( (a=strchr(iadr,':')) )
  2814.       *a='\0';
  2815.   }
  2816.  
  2817. #if HTS_WIN
  2818.   if (inet_addr(iadr)!=INADDR_NONE)  // numΘrique
  2819. #else
  2820.   if (inet_addr(iadr)!=(in_addr_t) -1 )  // numΘrique
  2821. #endif
  2822.     return 1;
  2823.  
  2824.   while(_hts_lockdns(-1));  // attendre libΘration
  2825.   _hts_lockdns(1);          // locker
  2826.   while(1) {
  2827.     if (strcmp(cache->iadr,iadr)==0) {  // ok trouvΘ
  2828.       _hts_lockdns(0);          // dΘlocker
  2829.       return 1;    // prΘsent!
  2830.     } else {    // on a pas encore trouvΘ
  2831.       if (cache->n!=NULL) { // chercher encore
  2832.         cache=cache->n;   // suivant!
  2833.       } else {
  2834.         _hts_lockdns(0);          // dΘlocker
  2835.         return 2;    // non prΘsent        
  2836.       }
  2837.     }    
  2838.   }
  2839. }
  2840.  
  2841. // cache dns interne α HTS // ** FREE A FAIRE sur la chaine
  2842. t_hostent* hts_gethostbyname(char* _iadr) {
  2843.   static char iadr[HTS_URLMAXSIZE*2];
  2844.   static t_hostent host;
  2845.   static char adr[HTS_URLMAXSIZE*2]="";  // buffer adr pour host
  2846.   static char* he[2];
  2847.   static unsigned long inetaddr;
  2848.   //
  2849.   t_dnscache* cache=_hts_cache();  // adresse du cache
  2850.   t_hostent* hp;
  2851.  
  2852.   strcpy(iadr,jump_identification(_iadr));
  2853.   // couper Θventuel :
  2854.   {
  2855.     char *a;
  2856.     if ( (a=strchr(adr,':')) )
  2857.       *a='\0';
  2858.   }
  2859.  
  2860.   // effacer structure de retour, crΘer nouvelle
  2861.   bzero((char *)&host,sizeof(t_hostent));  
  2862.   host.h_addr_list=he;
  2863.   he[0]=adr;
  2864.   he[1]=NULL;  
  2865.   host.h_length=0;  
  2866.   cache->iadr[0]='*';
  2867.   cache->iadr[1]='\0';
  2868.   
  2869.   /* get IP from the dns cache */
  2870.   hp = _hts_ghbn(cache,iadr,&host);
  2871.   if (hp) {
  2872.     if (hp->h_length>0)
  2873.       return hp;
  2874.     else
  2875.       return NULL;    // entrΘe erronΘe (erreur DNS) dans le DNS
  2876.   } else {  // non prΘsent dans le cache dns, tester
  2877.     t_dnscache* c=cache;
  2878.     while(c->n) c=c->n;    // calculer queue
  2879.     
  2880. #if HTS_WIDE_DEBUG    
  2881.     DEBUG_W("gethostbyname\n");
  2882. #endif      
  2883. #if HDEBUG
  2884.     printf("gethostbyname (not in cache)\n");
  2885. #endif
  2886.     {
  2887. #if HTS_WIN
  2888.       if ((inetaddr=inet_addr(iadr))==INADDR_NONE) {
  2889. #else
  2890.       if ((inetaddr=inet_addr(iadr))==(in_addr_t) -1 ) {
  2891. #endif        
  2892. #if DEBUGDNS 
  2893.         printf("resolving (not cached) %s\n",iadr);
  2894. #endif
  2895.         hp=gethostbyname(iadr);  // calculer IP host
  2896.       } else {     // numΘrique, convertir sans passer par le dns
  2897.         host.h_addr=(char*) &inetaddr;
  2898.         host.h_length=4;
  2899.         hp=&host;
  2900.       }
  2901.     }
  2902. #if HTS_WIDE_DEBUG    
  2903.     DEBUG_W("gethostbyname done\n");
  2904. #endif
  2905.     cache->n=(t_dnscache*) calloct(1,sizeof(t_dnscache));
  2906.     if (cache->n!=NULL) {
  2907.       strcpy(cache->n->iadr,iadr);
  2908.       if (hp!=NULL) {
  2909.         bcopy(hp->h_addr,cache->n->host_addr,hp->h_length);
  2910.         cache->n->host_length=hp->h_length;
  2911.       } else {
  2912.         cache->n->host_addr[0]='\0';
  2913.         cache->n->host_length=0;  // non existant dans le dns
  2914.       }
  2915.       cache->n->n=NULL;
  2916.       return hp;
  2917.     } else {  // on peut pas noter, mais on peut renvoyer le rΘsultat
  2918.       return hp;
  2919.     }        
  2920.   }  // retour hp du cache
  2921. }
  2922.  
  2923. #else
  2924. HTS_INLINE t_hostent* hts_gethostbyname(char* iadr) {
  2925.   t_hostent* retour;
  2926. #if HTS_WIDE_DEBUG    
  2927.   DEBUG_W("gethostbyname (2)\n");
  2928. #endif
  2929. #if DEBUGDNS 
  2930.     printf("blocking method gethostbyname() in progress for %s\n",iadr);
  2931. #endif
  2932.   retour=gethostbyname(jump_identification(iadr));
  2933. #if HTS_WIDE_DEBUG    
  2934.   DEBUG_W("gethostbyname (2) done\n");
  2935. #endif
  2936.   return retour;
  2937. }
  2938. #endif
  2939.  
  2940.  
  2941. // --- Tracage des mallocs() ---
  2942. #if HTS_TRACE_MALLOC
  2943. typedef struct _mlink {
  2944.   void* adr;
  2945.   int len;
  2946.   int id;
  2947.   struct _mlink* next;
  2948. } mlink;
  2949. mlink trmalloc = {NULL,0,0,NULL};
  2950. int trmalloc_id=0;
  2951.  
  2952. HTS_INLINE void* hts_malloc(size_t len,size_t len2) {
  2953.   mlink* lnk = (mlink*) calloc(1,sizeof(mlink));
  2954.   void*  r   = NULL;
  2955.   if (lnk) {
  2956.     if (len2)
  2957.       r = calloc(len,len2);
  2958.     else
  2959.       r = malloc(len);
  2960.     if (r) {
  2961.       lnk->adr=r;
  2962.       if (len2)
  2963.         lnk->len=len*len2;
  2964.       else
  2965.         lnk->len=len;
  2966.       lnk->id=trmalloc_id++;
  2967.       lnk->next=trmalloc.next;
  2968.       trmalloc.next=lnk;
  2969. #if MEMDEBUG
  2970.       //printf("malloc: %d\n",r);
  2971. #endif
  2972.     } else free(lnk);
  2973.   }
  2974.   return r;
  2975. }
  2976. HTS_INLINE void  hts_free(void* adr) {
  2977.   mlink* lnk = &trmalloc;
  2978.   if (!adr) {
  2979. #if MEMDEBUG
  2980.     printf("* unexpected free() error at %d\n",adr);
  2981. #endif
  2982.     return;
  2983.   }
  2984.   do {
  2985.     if (lnk->next->adr==adr) {
  2986.       mlink* blk_free=lnk->next;
  2987. #if 1
  2988.       lnk->next=lnk->next->next;
  2989.       free((void*) blk_free);
  2990. #else
  2991. #if MEMDEBUG
  2992.       if (blk_free->id==-1) {
  2993.         printf("* memory has already been freed: %d (id=%d)\n",blk_free->adr,blk_free->id);
  2994.       }
  2995. #endif
  2996.       blk_free->id=-1;
  2997. #endif
  2998.       free(adr);
  2999. #if MEMDEBUG
  3000.       //printf("free: %d (id=%d)\n",blk_free->adr,blk_free->id);
  3001. #endif
  3002.       return;
  3003.     }
  3004.     lnk=lnk->next;
  3005.   } while(lnk->next != NULL);
  3006. #if MEMDEBUG
  3007.   printf("* unexpected free() error at %d\n",adr);
  3008. #endif
  3009.   free(adr);
  3010. }
  3011. HTS_INLINE void* hts_realloc(void* adr,size_t len) {
  3012.   mlink* lnk = &trmalloc;
  3013.   do {
  3014.     if (lnk->next->adr==adr) {
  3015.       adr = realloc(adr,len);
  3016.       lnk->next->adr = adr;
  3017.       lnk->next->len = len;
  3018. #if MEMDEBUG
  3019.       //printf("realloc: %d (id=%d)\n",lnk->next->adr,lnk->next->id);
  3020. #endif
  3021.       return adr;
  3022.     }
  3023.     lnk=lnk->next;
  3024.   } while(lnk->next != NULL);
  3025. #if MEMDEBUG
  3026.   printf("* unexpected realloc() error at %d\n",adr);
  3027. #endif
  3028.   return realloc(adr,len);
  3029. }
  3030. // check the malloct() and calloct() trace stack
  3031. void  hts_freeall() {
  3032.   while(trmalloc.next) {
  3033. #if MEMDEBUG
  3034.     printf("* block %d\t not released: at %d\t (%d\t bytes)\n",trmalloc.next->id,trmalloc.next->adr,trmalloc.next->len);
  3035. #endif
  3036.     if (trmalloc.next->id != -1) {
  3037.       freet(trmalloc.next->adr);
  3038.     }
  3039.   }
  3040. }
  3041. #endif
  3042.  
  3043.  
  3044. // -- divers //
  3045.  
  3046. // cut path and project name
  3047. // patch also initial path
  3048. void cut_path(char* fullpath,char* path,char* pname) {
  3049.   path[0]=pname[0]='\0';
  3050.   if (strnotempty(fullpath)) {
  3051.     if ((fullpath[strlen(fullpath)-1]=='/') || (fullpath[strlen(fullpath)-1]=='\\'))
  3052.       fullpath[strlen(fullpath)-1]='\0';
  3053.     if (strlen(fullpath)>1) {
  3054.       char* a;
  3055.       while( (a=strchr(fullpath,'\\')) ) *a='/';     // remplacer par /
  3056.       a=fullpath+strlen(fullpath)-2;
  3057.       while( (*a!='/') && ((int) a > (int) fullpath)) a--;
  3058.       if (*a=='/') a++;
  3059.       strcpy(pname,a);
  3060.       strncat(path,fullpath,(int) a-(int) fullpath);
  3061.     }
  3062.   }
  3063. }
  3064.  
  3065.  
  3066.  
  3067. // -- Gestion protocole ftp --
  3068.  
  3069. #if HTS_WIN
  3070. int ftp_available() {
  3071.   return 1;
  3072. }
  3073. #else
  3074. int ftp_available() {
  3075.   return 1;   // ok!
  3076.   //return 0;   // SOUS UNIX, PROBLEMES
  3077. }
  3078. #endif
  3079.  
  3080.  
  3081. // Fin
  3082.  
  3083.